Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshape 3d matrix to 2d matrix

Tags:

I have a 3d matrix (n-by-m-by-t) in MATLAB representing n-by-m measurements in a grid over a period of time. I would like to have a 2d matrix, where the spatial information is gone and only n*m measurements over time t are left (ie: n*m-by-t)

How can I do this?

like image 275
Peter Smit Avatar asked Feb 13 '10 08:02

Peter Smit


People also ask

How to reshape 3D array to 2D array?

reshape() function to convert a 3D array with dimensions (4, 2, 2) to a 2D array with dimensions (4, 4) in Python. In the above code, we first initialize a 3D array arr using numpy. array() function and then convert it into a 2D array newarr with numpy. reshape() function.

How do you reshape commands in Matlab?

B = reshape( A , sz ) reshapes A using the size vector, sz , to define size(B) . For example, reshape(A,[2,3]) reshapes A into a 2-by-3 matrix. sz must contain at least 2 elements, and prod(sz) must be the same as numel(A) . B = reshape( A , sz1,...,szN ) reshapes A into a sz1 -by- ...

Can matrices be 3D?

A 3D matrix is nothing but a collection (or a stack) of many 2D matrices, just like how a 2D matrix is a collection/stack of many 1D vectors. So, matrix multiplication of 3D matrices involves multiple multiplications of 2D matrices, which eventually boils down to a dot product between their row/column vectors.


1 Answers

You need the command reshape:

Say your initial matrix is (just for me to get some data):

a=rand(4,6,8); 

Then, if the last two coordinates are spatial (time is 4, m is 6, n is 8) you use:

a=reshape(a,[4 48]); 

and you end up with a 4x48 array.

If the first two are spatial and the last is time (m is 4, n is 6, time is 8) you use:

a=reshape(a,[24 8]); 

and you end up with a 24x8 array.

This is a fast, O(1) operation (it just adjusts it header of what the shape of the data is). There are other ways of doing it, e.g. a=a(:,:) to condense the last two dimensions, but reshape is faster.

like image 67
Ramashalanka Avatar answered Sep 18 '22 07:09

Ramashalanka