Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collapse an array across a specific set of dimensions?

In Matlab, we can collapse across dimensions of an array like this:

M     = rand(3,4,5);
myvec = M(:);        % gives a 60-element vector

I think it's called serialising or flattening. The order of the elements is dim1 first, then dim2, then dim3 -- so you get [M(1,1,1); M(2,1,1); M(3,1,1); M(1,2,1); ...].

But what I want to do is collapse just along the first two dimensions:

mymatrix = M( :: , : ); % something that works like this?

to give a 12 x 5 matrix. So, for example, you get

[M(1,1,1)  M(1,1,2)  M(1,1,3)  M(1,1,4)  M(1,1,5)
 M(2,1,1)  M(2,1,2)  M(2,1,3)  M(2,1,4)  M(2,1,5)
 M(3,1,1)  M(3,1,2)  M(3,1,3)  M(3,1,4)  M(3,1,5)
 M(1,2,1)  M(1,2,2)  M(1,2,3)  M(1,2,4)  M(1,2,5)
 ...
]

So that the first dimension of mymatrix is the "flattened" 1st and 2nd dimensions of the original M, but preserving any other dimensions.

I actually need to do this for the "middle 3 dimensions" of a 5-dimensional array, so a general solution would be great! e.g. W=rand(N,N,N,N,N); mymatrix = W( :, :::, : ) should give a N x N^3 x N matrix if you see what I mean.

Thanks

like image 467
Sanjay Manohar Avatar asked Jun 24 '13 12:06

Sanjay Manohar


People also ask

What does Permute mean in Matlab?

Description. example. B = permute( A , dimorder ) rearranges the dimensions of an array in the order specified by the vector dimorder . For example, permute(A,[2 1]) switches the row and column dimensions of a matrix A . In general, the ith dimension of the output array is the dimension dimorder(i) from the input array ...

How many dimensions can an array have in VBA?

Although an array can have as many as 32 dimensions, it is rare to have more than three.

How do you shift dimensions in Matlab?

Description. B = shiftdim( A , n ) shifts the dimensions of an array A by n positions. shiftdim shifts the dimensions to the left when n is a positive integer and to the right when n is a negative integer. For example, if A is a 2-by-3-by-4 array, then shiftdim(A,2) returns a 4-by-2-by-3 array.

What determines the dimensions of the array?

The number of dimensions in an array is the same as the length of the size vector of the array.


1 Answers

Use reshape with square brackets ([]) as a placeholder for one of the dimension length arguments:

sz = size( M );
mymatrix = reshape( M, [], sz(end) );        % # Collapse first two dimensions

or

mymatrix = reshape( M, sz(1), [], sz(end) ); % # Collapse middle dimensions

The placeholder [] tells reshape to calculate the size automatically. Note that you can use only one one occurrence of []. All other dimension lengths must be specified explicitly.

like image 117
Shai Avatar answered Sep 28 '22 08:09

Shai