Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert matrix to cell array of cell arrays

Tags:

matlab

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?

like image 331
Steven Du Avatar asked Aug 12 '14 02:08

Steven Du


2 Answers

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.

like image 155
bla Avatar answered Nov 04 '22 07:11

bla


Just use elementary maths.

q = floor(123456/100);
r = rem(123456,100);
Output = mat2cell(x, 50, [repmat(100,1,q),r])
like image 42
Yvon Avatar answered Nov 04 '22 08:11

Yvon