What is it better?

1 次查看(过去 30 天)
gianluca
gianluca 2012-3-16
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

采纳的回答

Sean de Wolski
Sean de Wolski 2012-3-16
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 个评论
Jan
Jan 2012-3-16
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 2012-3-16
@Jan, I did a similar test. It appears to go left to right.

请先登录,再进行评论。

更多回答(1 个)

Daniel Shub
Daniel Shub 2012-3-16
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

类别

Help CenterFile Exchange 中查找有关 Clocks and Timers 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by