how to preallocate a variable

27 views (last 30 days)
sonam s
sonam s on 16 Mar 2014
Answered: dpb on 16 Mar 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

Accepted Answer

dpb
dpb on 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.

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!