how to preallocate a variable
27 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
dpb
le 16 Mar 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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!