Steven Du
Steven Du

Reputation: 1691

Convert matrix to cell array of cell arrays

I want to change a matrix N*123456 to a cells of cells, each sub-cell contains a N*L matrix

Eg:

matrixSize= 50*123456
N=50
L=100

Output will be 1*1235 cell and each cell has a 50*L matrix (last cell has only 50*56)

I know there is a function mat2cell in matlab:

Output = mat2cell(x, [50], [100,100,100,......56])

But it doesn't sound an intuitive solution.

So is there a good solution?

Upvotes: 5

Views: 972

Answers (2)

Yvon
Yvon

Reputation: 2983

Just use elementary maths.

q = floor(123456/100);
r = rem(123456,100);
Output = mat2cell(x, 50, [repmat(100,1,q),r])

Upvotes: 2

bla
bla

Reputation: 26069

If I understand you correctly, assuming your matrix is denoted m, this is what you wanted:

a=num2cell(reshape(m(:,1:size(m,2)-mod(size(m,2),L)),N*L,[]),1);
a=cellfun(@(n) reshape(n,N,L), a,'UniformOutput',false);
a{end+1}=m(:,end-mod(size(m,2),L)+1:end);

(this can be shortened to a single line if you wish)... Lets test with some minimal numbers:

m=rand(50,334);
N=50; 
L=100;

yields:

a = 
[50x100 double]    [50x100 double]    [50x100 double]    [50x34 double]

note that I didn't check for the exact dimension in the reshape, so you may need to reshape to ...,[],N*L) etc.

Upvotes: 4

Related Questions