필터 지우기
필터 지우기

What is it better?

조회 수: 2 (최근 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에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by