0

When I want to access a specific element of a matrix, I use indexing with parentheses:

m = calc_stuff(...);
x = m(index1, index2);

However, I often want to do that in one line of code, like this:

x = calc_stuff(...)(index1, index2);

How can I express it?

A specific example:

m = cumsum(rand(10,4));
x = m(10, 1);

The above script calculates some sums of random variables, and then I take one example value out of the result matrix.

How could I write it as one line? The following doesn't work:

x = cumsum(rand(10,4))(10, 1);

Error: ()-indexing must appear last in an index expression.

Here, I want a general syntax, which is applicable for any calculation, not necessarily involving random variables.

anatolyg
  • 24,991
  • 8
  • 55
  • 121

1 Answers1

0

You may want to check out the "Functional Programming Constructs" on the FileExchange).

Especially the file paren.m does what you need. So you would write

x = paren( cumsum(rand(10,4)), 10, 1 );

Perhaps not as elegant as the direct "()"notation, but that is not supported in MATLAB in the way you would like to use it.

Andreas H.
  • 4,920
  • 19
  • 27