How do I preallocate memory in a For loop code?

1 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2015-5-4
编辑:Stephen23 2015-5-4
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 2015-5-4
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?

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2015-5-4
编辑:Stephen23 2015-5-4
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by