how to preallocate a variable

29 Ansichten (letzte 30 Tage)
sonam s
sonam s am 16 Mär. 2014
Beantwortet: dpb am 16 Mär. 2014
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

Akzeptierte Antwort

dpb
dpb am 16 Mär. 2014
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.

Weitere Antworten (0)

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by