2

Consider the following matrix:

a=[1,2,3]

therefore

size(a)=[1,3]

I want to assign the second dimension 3 to variable n. What is the most efficient way?

Why are the following not working?

[[],n]=size(a)

or

  n= num2cell(size(a)){2}
Amro
  • 123,847
  • 25
  • 243
  • 454
godblessfq
  • 218
  • 1
  • 10
  • Seems like the most neat way is to use a temporary variable. http://stackoverflow.com/questions/3627107/how-can-i-index-a-matlab-array-returned-by-a-function-without-first-assigning-it?rq=1 – godblessfq Aug 15 '13 at 23:04

1 Answers1

2

This is probably the simplest, and works for a with any number of dimensions:

n = size(a,2);

If a is guaranteed to have exactly 2 dimensions, you could also use

[ m, n ] = size(a);

and if you don't need the first variable, in recent versions of Matlab you can write

[ ~, n ] = size(a);

As for the things you have tried:

  • [[],n]=size(a) does not work because [] is not a variable to which you can assign anything.

  • n= num2cell(size(a)){2} does not work because you can't directly index like that in Matlab. You would need a temporary variable: temp = num2cell(size(a)); n=temp{2}. Or dispose of num2cell and do: temp = size(a); n=temp(2).

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 2
    The first code is the correct one. Careful about the others, `size` will return the product of the remaining dimensions if you dont specify enough output variables; example: `x = rand(5,4,3,2); [~,n] = size(x);` (`n` will be equal to 4*3*2) – Amro Aug 16 '13 at 00:09
  • if you dont know the number of dimensions, another way is to do: `[~,n,~] = size(x)` this will work even if `ndims(x)==2`. Of course `size(x,2)` is the still the preferred way. – Amro Aug 16 '13 at 12:09
  • Also, `~` doesn't work for older versions of matlab. Specifically R2009a on my laptop, not sure about other revisions. – JustinBlaber Aug 16 '13 at 16:16