How do I preallocate memory in a For loop code?

1 回表示 (過去 30 日間)
Fun Dan
Fun Dan 2015 年 5 月 4 日
編集済み: Stephen23 2015 年 5 月 4 日
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.
  1 件のコメント
Fun Dan
Fun Dan 2015 年 5 月 4 日
Thanks Stephen. I appreciate.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by