llll0
llll0

Reputation: 115

Converting nxm matrix into a 1xm cell array

How can I convert a 2xn matrix into a 1xn cell array, concatenating the values upwards so the cell array contains the column vectors of the original matrix? I want to do this more efficiently than a simple for loop going through each column (as this is matlab and loops are inefficient)

Say I had a 2x2 matrix [1,2;3,4]. I wish to convert it into a cell array {[1,3],[2,4]}. I have looked up about mat2cell but can't see how to keep the length of the cell array while concatenating upwards.

Thanks in advance.

Upvotes: 0

Views: 547

Answers (2)

surgical_tubing
surgical_tubing

Reputation: 148

Kind of a dense line, but I think this does what you're after.

A=[1 2;3 4];
permute(mat2cell(reshape(permute(A,[2 1]),[numel(A) 1]),size(A,1)*ones(size(A,2),1),[1] ),[2 1])

Upvotes: 0

Benoit_11
Benoit_11

Reputation: 13945

You can take advantage of additional arguments to mat2cell to format the output as you like.

In your case, specify that each cell contains 2 element in a row:

A = [1 2;3 4];
B = mat2cell(A.',[1 1]).';

celldisp(B)

B is now a 1x2 cell:

B{1} =

     1     3



B{2} =

     2     4

Upvotes: 1

Related Questions