danjoro
danjoro

Reputation: 111

How to convert matrix to cell array

I have matrix A = 50x2 How to convert the data into cell array. Should be I have 10 cell which each cell contain data [5x2].

Thank you for help.

Upvotes: 1

Views: 1303

Answers (2)

Dev-iL
Dev-iL

Reputation: 24159

One can use num2cell:

N_ROWS = 5; N_COLS = 2;
A = rand(50,2);
B = num2cell(reshape(A,N_ROWS,N_COLS,[]),[1,2]); % B is 1x1x10 cell array

What this does is turn your input array into 5x2 "slices" stacked along the 3rd dimension.

You can add a squeeze(B), B = B(:) or a reshape(B,[],1) at the end if you need the output as a column vector.

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112659

That is what mat2cell does:

A = rand(50,2); % example matrix
N = 10; % number of cells in which to split the first dimension
result = mat2cell(A, repmat(size(A,1)/N, 1, N), size(A,2));

Upvotes: 2

Related Questions