1
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.

Aleksejs Fomins
  • 688
  • 1
  • 8
  • 20

2 Answers2

3

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)).

gnovice
  • 125,304
  • 15
  • 256
  • 359
2

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}})))
Marco
  • 2,007
  • 17
  • 28
  • This answers the question, hence the upvote, but I would not recommend doing this, using two lines is a lot clearer! :) – Cris Luengo Feb 19 '18 at 19:42
  • @CrisLuengo I would opt for 2 lines – or `size(a, 2)` – as well... This one works but is very ugly. – Marco Feb 19 '18 at 19:45
  • I agree, this is formally exactly what I have asked for, as it turns out only to confirm I should not use it :D – Aleksejs Fomins Feb 20 '18 at 12:11