What is it better?
Show older comments
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
Accepted Answer
More Answers (1)
Daniel Shub
on 16 Mar 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
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!