How can I index a MATLAB array returned by a function without first assigning it to a local variable?

It actually is possible to do what you want, but you have to use the functional form of the indexing operator. When you perform an indexing operation using (), you are actually making a call to the subsref function. So, even though you can't do this:

value = magic(5)(3, 3);

You can do this:

value = subsref(magic(5), struct('type', '()', 'subs', {{3, 3}}));

Ugly, but possible. ;)

In general, you just have to change the indexing step to a function call so you don't have two sets of parentheses immediately following one another. Another way to do this would be to define your own anonymous function to do the subscripted indexing. For example:

subindex = @(A, r, c) A(r, c);     % An anonymous function for 2-D indexing
value = subindex(magic(5), 3, 3);  % Use the function to index the matrix

However, when all is said and done the temporary local variable solution is much more readable, and definitely what I would suggest.


There was just good blog post on Loren on the Art of Matlab a couple days ago with a couple gems that might help. In particular, using helper functions like:

paren = @(x, varargin) x(varargin{:});
curly = @(x, varargin) x{varargin{:}};

where paren() can be used like

paren(magic(5), 3, 3);

would return

ans = 16

I would also surmise that this will be faster than gnovice's answer, but I haven't checked (Use the profiler!!!). That being said, you also have to include these function definitions somewhere. I personally have made them independent functions in my path, because they are super useful.

These functions and others are now available in the Functional Programming Constructs add-on which is available through the MATLAB Add-On Explorer or on the File Exchange.


How do you feel about using undocumented features:

>> builtin('_paren', magic(5), 3, 3)               %# M(3,3)
ans =
    13

or for cell arrays:

>> builtin('_brace', num2cell(magic(5)), 3, 3)     %# C{3,3}
ans =
    13

Just like magic :)


UPDATE:

Bad news, the above hack doesn't work anymore in R2015b! That's fine, it was undocumented functionality and we cannot rely on it as a supported feature :)

For those wondering where to find this type of thing, look in the folder fullfile(matlabroot,'bin','registry'). There's a bunch of XML files there that list all kinds of goodies. Be warned that calling some of these functions directly can easily crash your MATLAB session.