how to efficiently vectorize nested for loops

4 Ansichten (letzte 30 Tage)
M.R
M.R am 2 Sep. 2019
Kommentiert: M.R am 4 Sep. 2019
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

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by