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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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)
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.
Also, ~ doesn't work for older versions of matlab. Specifically R2009a on my laptop, not sure about other revisions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.