Santhan Salai
Santhan Salai

Reputation: 3898

How to retrieve specific dimensions using size() function in Matlab

Here is an example matrix A of Dimensions 6x3x8x5

Now if i use size(A), i get all the dimensions as a row vector

ans = [6 3 8 5]

If i want to get specific dimension(singular), i could use something like size(A,1) or size(A,3) etc..

What if i want specified set of dimensions for eg, size of 3rd and 4th dimensions or 2nd to nth dimension

What i want to do is something like size(A,3:4) or size(A,2:n) or size(A,[1 3 4])

But from the Doc, it appears that, input dimensions for size could only be a scalar. When i try to do this, i get this error:

>> size(A,[2 3])

Error using size
Dimension argument must be a positive integer scalar within indexing range.

I'm expecting the output to be

ans = [3 8]

FYI:

I'm trying to pass this as an input argument into another function like this:

out = someFunction(arg1,arg2,size(A,[2 3]))

What i'm currently doing is

[~,size2,size3,~] = size(A)

out = someFunction(arg1,arg2,[size2, size3])

I just wanted to use it directly without the first line. Obviously when we have only two dimensions, we use it directly just by doing size(A). why not in this case? Any alternative to make this a one-liner?

Upvotes: 2

Views: 2038

Answers (2)

Robert Seifert
Robert Seifert

Reputation: 25232

Both Troy Haskin's answers and mine are borrowed from this question: How can I index a MATLAB array returned by a function without first assigning it to a local variable? I personally find the getfield approach appropriate for your case, where you just wrap getfield around your size function:

A = randn(1,2,3,4,5);   %// 5D double

out = getfield(size(A),{[2 3]})

out =

     2     3

Using subsref is probably the better approach as more direct and faster, but it could make your code less readable, as it is very specific hack.

Upvotes: 3

TroyHaskin
TroyHaskin

Reputation: 8401

That's just the way size is written.

If you wanted a one-liner, you can use subsref to index the one-output form of size:

out = someFunction(arg1,arg2,...
              subsref(size(A),struct('type','()','subs',{{[2,3]}})));

And if you're going to be doing this a lot, add a function somewhere on the Matlab path or make an line one:

sizes = @(A,dims) subsref(size(A),struct('type','()','subs',{{dims}}));
out   = someFunction(arg1,arg2,sizes(A,[2,3]));

You can also create sizes without a direct call to subsref by a little indirection with function handles:

getSizes = @(d,s) d(s);
sizes    = @(A,s) getSizes(size(A),s);

which may be clearer and more maintainable.

Upvotes: 4

Related Questions