For example, if I want to read the middle value from magic(5)
, I can do so like this:
M = magic(5);
value = M(3,3);
to get value == 13
. I'd like to be able to do something like one of these:
value = magic(5)(3,3);
value = (magic(5))(3,3);
to dispense with the intermediate variable. However, MATLAB complains about Unbalanced or unexpected parenthesis or bracket
on the first parenthesis before the 3
.
Is it possible to read values from an array/matrix without first assigning it to a variable?
Best Answer
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 thesubsref
function. So, even though you can't do this:You can do this:
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:
However, when all is said and done the temporary local variable solution is much more readable, and definitely what I would suggest.