MasterPJ
MasterPJ

Reputation: 389

append (distribute) variables from a matrix into to a cell array

I am using function meshgrid to create 2 matrixes and function num2cell to make a cell array from one matrix.

latVectr = 1:1:5;
longVectr = 10:2:20;
[X,Y] = meshgrid(latVectr,longVectr);

CELX = num2cell(X);

I would like to distribute the variables of the second matrix to the cells of the created cell array as following:

X{1,1}(1,2) = Y(1,1);
X{1,2}(1,2) = Y(1,2);
;
;
;
;X(n,m)(1,1) = Y(n,m)

I can do it with a loop. Is there any other more elegant way how to do it?

Upvotes: 1

Views: 118

Answers (2)

Shai
Shai

Reputation: 114826

Another approach using cellfun

CELX = cellfun(@(x,y) [x,y], num2cell(X), num2cell(Y), 'UniformOutput', false );

In fact, I feel this solution is more elegant than my other solution

Upvotes: 1

Shai
Shai

Reputation: 114826

It seems like you wish CELX{ k, l } will be [ X(k,l) Y(k,l) ].
This can be done through

CELX = mat2cell( cat(3, X, Y ), ones(size(X,1),1), ones(1, size(X,2)), 2 );

EDIT:
You may want to correct for the dimensionality of the resulting cells using

CELX = cellfun( @squeeze, CELX, 'UniformOutput', false );

Upvotes: 1

Related Questions