views:

430

answers:

2

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?

+4  A: 

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.

Ramashalanka
+3  A: 

Reshape is of course the standard solution to reshaping an array. (What else would they call it?) There are still a few tricks to uncover.

First of all, the simplest way to turn an array of size [n,m,p] into an array of size [n*m,p]?

B = reshape(A,n*m,p);

But better is this:

B = reshape(A,[],p);

If you leave one of the arguments to reshape empty, then reshape computes the size for you! Be careful, if you try this and the size of A does not conform, then you will get an error. Thus:

reshape(magic(3),[],2)
??? Error using ==> reshape
Product of known dimensions, 2, not divisible into total number of elements, 9.

Logically, we cannot create an array of with two columns from something that has 9 elements in it. I did put a function called wreshape on the MATLAB Central exchange that would pad as necessary to do this operation with no error generated.

Of course, you can always use tricks like

B = A(:);

to create a vector directly from a matrix. This is equivalent to the form

B=reshape(A,[],1);
woodchips

related questions