How do I preallocate memory in a For loop code?
1 view (last 30 days)
Show older comments
How do I preallocate memory for the for loop below? And does preallocating memory makes a simulation run faster?
#1 for Mx = x:50:500;
#2 for My = y:50:400;
#3 %
#4 J1 = [sqrt((Mx-100)^2+(My-20)^2)];
#5 J2 = [sqrt((Mx-20)^2+(My-150)^2)];
#6 J3 = [sqrt((Mx-50)^2+(My-450)^2)];
#7 J4 = [sqrt((Mx-150)^2+(My-450)^2)];
#8 J5 = [sqrt((Mx-7000)^2+(My-200)^2)];
#14 end
#15 end
Thanks
2 Comments
Accepted Answer
Stephen23
on 4 May 2015
Edited: Stephen23
on 4 May 2015
x = 0;
y = 0;
Vx = x:50:500;
Vy = y:50:400;
Cx = [100,20,50,150,7000];
Cy = [20,150,450,450,200];
Tx = bsxfun(@minus,reshape(Vx,1,[],1),Cx(:)).^2;
Ty = bsxfun(@minus,reshape(Vy,1,1,[]),Cy(:)).^2;
out = sqrt(bsxfun(@plus,Tx,Ty));
where the final variable out is arranged with the constants Cx and Cy along the first dimension (rows), then Vx values along the second dimension (columns), and Vy along the third dimension (pages):
>> size(out)
ans =
5 11 9
And to answer your question "does preallocating memory makes a simulation run faster?", then answer is yes! In most cases array preallocation will give much faster code than without array preallocation. MATLAB clearly describes and recommends this in their documentation:
But you don't have to ask here: try it yourself! Make a small experiment with the same operation in a loop and the same one with preallocation... and you will discover the difference yourself.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!