I'm optimizing some code at the moment and can't figure out a way to go faster than MATLAB's cell2mat. For now, the multiple uses of cell2mat in my code represent more than 15% of the processing time.
I think it can go faster than that, because i know the structure of the cell arrays i'll pass to the function.
Basically, the cell array is NxN, where :
The top left
(N-1)x(N-1)block contains, in each cell, a6x6double matrixThe bottom right
(N,N)cell is aMxMdouble matrix.The other cells have the right dimensions for concatenating, i.e. :
The cells (1:(N-1),N) are 6xM double matrices, the cells (N,1:(N-1)) are Mx6 double matrices. (Image added for the sake of clarity, there N=207 and M=300)
As the cells will always be filled with doubles AND always be of dimension 2, i'm already only using a small piece of the cell2mat code, i.e. :
function m = myCell2Mat(c)
rows = size(c,1);
m = cell(rows,1);
% Concatenate one dim first
for n=1:rows
m{n} = cat(2,c{n,:});% 73% of the time spent here
end
% Now concatenate the single column of cells into a matrix
m = cat(1,m{:});% 25.2% of the time spent there
end
This doens't change the time spent much as (like one could imagine), the most time is spent on these lines.
My question is : Does anyone have an idea about how to remove the loop there? I tried something along the lines of :
N=207;
M=300;
C=cell(N,N);
for ii=1:N-1
for jj=1:N-1
C{ii,jj}=rand(6);
end
end
for kk=1:(N-1)
C{N,kk}=rand(M,6);
C{kk,N}=rand(6,M);
end
C{end}=rand(M,M);
tmp1=cat(1,C{:,1:(end-1)});
LeftPart=reshape(tmp1,[],6*(size(C,2)-1));
RightPart=cat(1,C{:,end});
Res=[LeftPart RightPart];
But it doesn't show any improvment in time.. (And gives a false result as the reshape operates columnwise)
I've thought about using a recursive function aswell but it doesn't seem to be going anywhere.
Thanks in advance!

cell2matwithout the error checking.cell2matis optimised for 2D cells, so I don't think you will get much of a speed up. - IKavanagh.mfiles can be viewed withedit cell2mat. Those implemented as built-in (C) functions will say they are built-in and you won't be able to view their source. - IKavanagh(N-1)x(N-1)could be stored as a4D-Matrixmatrix which is typically faster than a cell. - Daniel