how to efficiently vectorize nested for loops

4 次查看(过去 30 天)
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().

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by