|
I have cells of different lengths,
Let's say,
A={[1:4];[1:5];[1:2]};
I am trying to make this into one matrix by completing the empty spaces with 0.
So A looks like this,
1 2 3 4 0
1 2 3 4 5
1 2 0 0 0
I am using the following code, (S_Seq is a cell of 5x1 with each cell being a (12x1 cell),
[Eij_CM tf] = padcat(S_Seq{s,1}{:});
Eij_CM(~tf) = 0;
padcat is in the FEX.
The thing is I am calling this line 1656000 times, taking a total of 319.317 sec.
I tried changing it to this code but takes longer,
lns = cellfun(@length,S_Seq{s,1});
mx = max(lns);
mat = 0;
for ii = 1:numel(S_Seq{s,1})
S_Seq{s,1}{ii,1} = [S_Seq{s,1}{ii,1} mat(1,ones(1,mx-lns(ii)))];
end
cell2mat(S_Seq{s,1})
If anyone has a clue how I can run this faster it would make my code a hell lot better! Thanks! Any questions or clarifications let me know!
FYI padcat function is,
function [M, TF] = padcat(varargin)
error(nargchk(1,Inf,nargin)) ;
SZ = cellfun(@size,varargin,'UniformOutput',false) ; % sizes
Ndim = cellfun(@ndims,varargin) ; %
if ~all(Ndim==2)
error([mfilename ':WrongInputDimension'], ...
'Input should be vectors.') ;
end
TF = [] ; % default second output so we do not have to check all the time
SZ = cat(1,SZ{:}) ;
maxSZ = max(SZ) ; % probable size of the longest vector
if ~any(maxSZ == 1), % hmm, not all elements are 1-by-N or N-by-1
if any(maxSZ==0),
M = [] ;
return
else
error([mfilename ':WrongInputSize'], ...
'Inputs should be all row vectors or all column vectors.') ;
end
end
if nargin == 1,
M = varargin{1} ;
else
dim = (maxSZ(1)==1) + 1 ; % Find out the dimension to work on
X = cat(dim, varargin{:}) ; % make one big list
if maxSZ(dim) == 1,
M = X ; % copy the list
elseif all(SZ(:,dim)==SZ(1,dim)),
M = reshape(X,SZ(1,dim),[]) ;% copy the list and reshape
else
M = zeros([maxSZ(dim)+1 nargin]) ;
M(sub2ind(size(M), SZ(:,dim).'+1, 1:nargin)) = 1 ;
M = cumsum(M(1:end-1,:),1) ; % remove last row
if nargout>1,
TF = ~M ;
M(~TF) = NaN ; % put the fillers in
M(TF) = X ; % put the values in
else
M(M==1) = NaN ; % put the fillers in
M(M==0) = X ; % put the values in
end
end
if dim == 2,
M = M.' ;
TF = TF.' ;
end
end % nargin == 1
if nargout > 1 && isempty(TF),
TF = true(size(M)) ;
end
|