how to efficiently vectorize nested for loops

4 views (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 2 Sep 2019
Edited: Walter Roberson on 2 Sep 2019
[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 Comment
M.R
M.R on 4 Sep 2019
this works for me. thank you. and also i enjoyed the brevity of the code.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!