How do I preallocate memory in a For loop code?

1 view (last 30 days)
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
Stephen23
Stephen23 on 4 May 2015
Edited: Stephen23 on 4 May 2015
Note that those brackets [] are unnecessary (as the Editor highlighting and message also tells you). There is nothing being concatenated tougher, so they just slow the code down.
Fun Dan
Fun Dan on 4 May 2015
Thanks Stephen. I took the [] out. I was getting low memory error so I thought if I preallocate a memory that would solve the issue. Also, I notice my simulation keeps running longer than it should, could that be the issue?

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 4 May 2015
Edited: Stephen23 on 4 May 2015
Here is a completely vectorized code version using bsxfun:
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)

Categories

Find more on Programming 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!