how to efficiently vectorize nested for loops

4 ビュー (過去 30 日間)
M.R
M.R 2019 年 9 月 2 日
コメント済み: M.R 2019 年 9 月 4 日
Hi everyone,
I am practicing vectorize programing and i faced a code that became a challenge for me,
this is the code in normal mode which runs correctly:
for t = 1:N
A(t,:) = a; B(t,:) = b; C(t,:) = c;
S = 0;
for i=1:2
for j=1:2
for k=1:2
M =((-1) ^ i).*((-1) ^ j).*((-1) ^ k);
R = sqrt((a(i))^2+(b(j))^2+(c(k))^2);
N = atan( (a(i) * b(j)) / (c(k) * R) );
S = S + R*sin(N/M);
end
end
end
end
here A,B and C are (N*2) data arrays.
first i dont know the general strategy when having more than 2 for loops.
and how can i rewrite the terms M and R and N for this example how can i write this code in effective way.
Thank you

採用された回答

Walter Roberson
Walter Roberson 2019 年 9 月 2 日
編集済み: Walter Roberson 2019 年 9 月 2 日
[aG, bG, cG] = ndgrid(a, b, c);
[iG, jG, kG] = ndgrid(1:size(a,2), 1:size(b,2), 1:size(c,2));
M = (-1).^(iG + jG + kG);
R = sqrt(aG.^2 + bG.^2 + cG.^2);
N = atan2(aG .* bG, cG .* R);
RS = R .* sin(N .* M); %with M being -1 or +1, multiplication is faster than division
S = sum(RS(:));
However, please check your equations to see whether atan2(y,x) makes sense instead of atan(y./x). The difference would be in the quadrant, which would affect the sign of the sin().
  1 件のコメント
M.R
M.R 2019 年 9 月 4 日
this works for me. thank you. and also i enjoyed the brevity of the code.

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

その他の回答 (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