How to collapse an array according to a specific set of parameters?

In Matlab, we can collapse all array sizes as follows:

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

I think it was called serialization or flattening. First the order of elements dim1, then dim2, then dim3 - so you get [M(1,1,1); M(2,1,1); M(3,1,1); M(1,2,1); ...] [M(1,1,1); M(2,1,1); M(3,1,1); M(1,2,1); ...] [M(1,1,1); M(2,1,1); M(3,1,1); M(1,2,1); ...] .

But what I want to do is collapse only in the first two dimensions:

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

to get 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, the first size of mymatrix is the “flattened” 1st and 2nd dimensions of the original M , but with the preservation of any other dimensions.

I really need to do this for the “average 3 dimensions” of a 5-dimensional array, so the general solution would be great! for example, W=rand(N,N,N,N,N); mymatrix = W( :, :::, : ) W=rand(N,N,N,N,N); mymatrix = W( :, :::, : ) should give the matrix N x N^3 x N , if you understand what I mean.

thanks

+6
source share
1 answer

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 calculate the size automatically. Please note that you can use only one event [] . All other dimensional lengths must be indicated explicitly.

+5
source

Source: https://habr.com/ru/post/947991/


All Articles