M_A
M_A

Reputation: 13

Creating multiple matrices from one large matrix

I have a matrix (mxnxk) where mxn are the data corresponding to specific latitude and longitude and k refers to the time.

I am trying to generate k matrices where each on is mxn so then I will have a matrix for each time step.

Is that possible with MATLAB?

Upvotes: 1

Views: 183

Answers (2)

Cris Luengo
Cris Luengo

Reputation: 60504

Given a 3D matrix X:

X = randn(10, 7, 4);

it is possible to split it out into individual planes, and store them all in a cell array, as follows:

C = mat2cell(X, size(X,1), size(X,2), ones(size(X,3),1));

Now, the array X(:,:,k), the kth time step, is C{k}.

There are other ways to split out such a 3D array, and other ways to store each of the resulting 2D arrays, but this method is the simplest that I'm aware of.

There might not be a big difference in the syntax X(:,:,k) vs C{k}. If you repeatedly need to access each of the 2D arrays, the latter is more efficient, as the former needs to make a copy. If you only access each of them once, you will be better off extracting them as you need them, rather than creating the cell array.

Upvotes: 2

selene
selene

Reputation: 384

Other more advanced users may chime in with a better/more efficient way to do this, but I think I understand what you are asking and a possible way to do it (I'm curious as to other suggestions!)

Creating new variable names in a loop isn't straightforward in matlab, but, if you make them parts of structures then you can kind of work around it.

if A is your m*n*k matrix,

s = struct;

for i = 1:k
s.(['k' num2str(i)]) = A(:,:,k); % builds a field in structure s named k#
end

This should make a structure, s, that has s.k1, s.k2, s.k3, etc each of which is just an m*n matrix.

Then if you need to do other things later to all of the parts of s, you can call them in the same way using s.(['k' num2str(i)])

Upvotes: 1

Related Questions