How to optimize this code by avoiding nested for loops?

1 回表示 (過去 30 日間)
Canberk Suat Gurel
Canberk Suat Gurel 2018 年 4 月 12 日
回答済み: Walter Roberson 2018 年 4 月 12 日
Hi all,
I have written the following code, whose Elapsed time is 32.427771 seconds.
t=1;
ObsX=[]; ObsY=[];
tic
for i = 3.53:0.0001:4.67
for j = -6.17:0.0001:-4.53
ObsX(t) = j;
ObsY(t) = i;
t=t+1;
end
end
toc
I have rectangular obstacle with the coordinates 3.53:4.67 and -6.17:-4.53 and the resolution is 0.0001. I am trying to store the X coordinates in array ObsX and Y coordinates in array ObsY.
Can you suggest way to improve the computation time? Thanks!

採用された回答

Walter Roberson
Walter Roberson 2018 年 4 月 12 日
[X, Y] = ndgrid(3.53:0.0001:4.67, -6.17:0.0001:-4.53);
ObsX = X(:);
ObsY = Y(:);
Note: I did not check to be sure that the values are in the same order as you created. You might need meshgrid() instead of ndgrid()

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGet Started with Optimization Toolbox についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by