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
  • 26,506
  • 9
  • 60
  • 134
  • Octave allows to do this, but in Matlab you need to use `subsref`. Check @Sardar_Usama link for a complete explanation –  Nov 15 '16 at 12:33
  • If you just want to put it on one line, separate the two lines with a semicolon and put them on one line. E.g. `m = calc_stuff(...); x = m(index1, index2);` – Sebastian Nov 13 '22 at 20:01

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.
  • 5,557
  • 23
  • 32