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?
You need the command
reshape
:Say your initial matrix is (just for me to get some data):
Then, if the last two coordinates are spatial (time is 4, m is 6, n is 8) you use:
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:
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.A better solution to this problem is to use nshape.m available from Rasmus Bro's N-Way Toolbox. That will allow you to reshape along a given mode, which is a little more tricky with the reshape command.
The toolbox is available at the following link:
https://www.mathworks.com/matlabcentral/fileexchange/1088-the-n-way-toolbox
There are some other excellent tools there to help with array manipulation as well.
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]?
But better is this:
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:
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
to create a vector directly from a matrix. This is equivalent to the form