how to efficiently vectorize nested for loops
4 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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().
More Answers (0)
See Also
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!