What is it better?

1 visualización (últimos 30 días)
gianluca
gianluca el 16 de Mzo. de 2012
From the computational point of view, is it better one cycle for with following if statements, or several cycles for for each if statement? I think it's better this:
for i = 1:length(GR)
if tool == 1
Bmud(i,1) = B_3_c(1,1) .* (rho(i,1) .* 8.345) + B_3_c(2,1);
elseif tool == 2
Bmud(i,1) = B_3_e(1,1) .* (rho(i,1) .* 8.345) + B_3_e(2,1);
end
end
than
if tool == 1
for i = 1:length(GR)
Bmud(i,1) = B_3_c(1,1) .* (rho(i,1) .* 8.345) + B_3_c(2,1);
end
elseif tool == 2
for i = 1:length(GR)
Bmud(i,1) = B_3_e(1,1) .* (rho(i,1) .* 8.345) + B_3_e(2,1);
end
end

Respuesta aceptada

Sean de Wolski
Sean de Wolski el 16 de Mzo. de 2012
The second one. Every computation you can pull outside fo a for-loop is a good thing!
Also note this can be easily vectorized, for example with tool==2
Bmud(1:length(GR),1) = B_3_e(1,1) .* (rho(1:length(GR),1) .* 8.345) + B_3_e(2,1);
  3 comentarios
Jan
Jan el 16 de Mzo. de 2012
No, Matlab is not smart for the ordering: it multiplies from left to right. Therefore:
A = rand(2000); b = rand; c = rand;
tic; for i=1:100; B = A * b * c; clear('B'); end; toc
tic; for i=1:100; B = A * (b * c); clear('B'); end; toc
tic; for i=1:100; B = (A * b) * c; clear('B'); end; toc
Sorry, I cannot measure it currently, because the virus-scanner has hijacked my machine.
Daniel Shub
Daniel Shub el 16 de Mzo. de 2012
@Jan, I did a similar test. It appears to go left to right.

Iniciar sesión para comentar.

Más respuestas (1)

Daniel Shub
Daniel Shub el 16 de Mzo. de 2012
I hope this is not homework ...
With only a single for loop you make the tool==1 comparison length(GR) times, while in the dual loop case you only make it once. So there is a slight computational edge. As there are only two multiplications and an addition within the loop (assuming B_3_* are matrices and not functions) that comparison may be a non-trival portion of your compute time ...
Ideally you want to get as much work outside the loop as possible, so a better approach would be:
if tool == 1
m = B_3_c(1, 1).*8.345;
b = B_3_c(2, 1);
N = length(GR);
elseif tool == 2
m = B_3_e(1, 1).*8.345;
b = B_3_e(2, 1);
N = length(GR);
else
N = 0;
end
Bmud = nan(length(GR), 1); % You may have already done the intialization ...
for i = 1:N
Bmud(i, 1) = m*rho(i, 1)+b;
end
So the loop only has 1 multiplication and 1 addition instead of 2 multiplications.
The MATLAB answer of course is to get rid of the loop completely.
if tool == 1
Bmud = (8.345.*B_3_c(1,1).*rho(1:length(GR),1))+B_3_c(2,1);
elseif tool == 2
Bmud = (8.345.*B_3_e(1,1).*rho(1:length(GR),1))+B_3_e(2,1);
end

Categorías

Más información sobre Clocks and Timers en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by