0
votes

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.

2

2 Answers

1
votes

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
0
votes

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])