Reshape 3d matrix to 2d matrix

Peter Smit picture Peter Smit · Feb 13, 2010 · Viewed 57.3k times · Source

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?

Answer

Ramashalanka picture Ramashalanka · Feb 13, 2010

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.