MATLAB: What is it better

forif

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

Best Answer

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);