how to preallocate a variable
28 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Akzeptierte Antwort
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.
0 Kommentare
Weitere Antworten (0)
Siehe auch
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!