Aleksejs Fomins
Aleksejs Fomins

Reputation: 900

Matlab access array element in one line

a = 0:99
s = size(a)
disp(s(2))

Can the last two lines be written as one? In other languages I am able to do f(x)[i], but Matlab seems to complain.

Upvotes: 1

Views: 215

Answers (2)

gnovice
gnovice

Reputation: 125854

In this specific case where you are using the size function, you can add an additional argument to specify the dimension you want the size of, allowing you to easily do this in one line:

disp(size(a, 2));  % Displays the size of the second dimension

In the more general case of accessing an array element without having to store it in a local variable first, things get a little more complicated, since MATLAB doesn't have the same kind of indexing shorthand you would find in other languages. Octave, for example, would allow you to do disp(size(a)(2)).

Upvotes: 3

Marco
Marco

Reputation: 2092

It is possible to collapse those two lines in one single statement and achieve a sort of f(x)[i] thanks to the functional form of the indexing operator: subsref.

disp(subsref(size(a), struct('type', '()', 'subs', {{2}})))

Upvotes: 2

Related Questions