Reputation: 249
I am trying to allocate space to my for loop but it just won't work.
I have looked at all the similar questions and matlab help and it doesn't make any difference. I must be missing something.
xt = [];
yt = [];
for ii = 1:size(result,1)
x = result{ii,1}(:,1);
xt = [xt;x];
y = result{ii,1}(:,2);
yt = [yt;y];
end
And my attempt at precollacting space for xt has been
xt = zeros(size(result,1),1);
with no results. I think my problem might be that result
is a cell array??
Upvotes: 0
Views: 46
Reputation: 35525
If you concatenate you don't need to prealocate. If you prealocate don't concatenate!
xt = [xt;x];
The previous line will take xt
, will put x
amount of NEW values in the end of it, appended. It will not substitute the values of xt
.
To be able to allocate memory for different sizes of a cell array youll need to know the number of elements of each one.
sizes=zeros(size(result,1),1);
for ii=1:size(result,1)
sizes(ii)=size(result{ii},1); %//get the size of the matrix
end
%// now we know the sizes
xt=zeros(sum(sizes),1); %the total number is the sum of each of them
%// handle the first special case
xt( 1:sizes(1) )=result{1,1}(:,1);
%// add the rest
for ii = 2:size(result,1)
xt( 1+sum(sizes(1:ii-1)) : sum(sizes(1:ii)) )= result{ii,1}(:,1);
end
Upvotes: 2