how to preallocate a variable

15 次查看(过去 30 天)
sonam s
sonam s 2014-3-16
回答: dpb 2014-3-16
a1=('a':'z').'; b1=('A':'Z').';
for i=1:52
if(i<=26)
a(i)=a1(i);
i=i+1;
end;
if(i>26)
a(i)=b1(i-26);
i=i+1;
end;
end;
*in the above code it is getting warning as "a might be growing inside a loop.consider preallocating for speed." *
what is meant by that and please help me how to rectify it

采纳的回答

dpb
dpb 2014-3-16
It means you're building an array ( a in this case) an element at a time. To do that means that each pass thru the loop the array is augmented by another element causing the previous array to be copied to a new one, the new value inserted and the the old one deallocated. That's a lot of excess overhead when one knows a priori the size of the resulting array.
To preallocate, before you start the loop, just write
a=zeros(52,1);
then you can just populate it w/o causing the reallocation.
But, in Matlab, look to vectorize and eliminate loops entirely -- in your case just write
a=['a':'z' 'A':'Z'].';
and be done with it.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by