MATLAB: Is vectorizing way slower than the for-next loop it replaced

for loopMATLABperformancespeedvectorization

You're recomputing the logical tests multiple times for one thing. I count nine (9) times overall and as many as three (3) of the same result.
Sometimes for loops are just as fast or faster; in the end the compile code has to come down to looping construct for actual execution.
I would think the optimizer would detect those in the same line, not sure it can/will do so over the full function.
iz=(z<=200);
ea(iz)=0;
ea(~iz)=eds(~iz).*(z(~iz)-200)/100;
iz=(z<=100);
td(~iz)=tdo;
td(iz)=tdo*z(iz)/100;
Don't know if will be appreciably faster or not…

Best Answer

The for-loop you've shown is only 4 iterations long (i=1:4). I suspect that's because you abbreviated the loop for testing purposes and forgot to revert back when comparing to the vectorized version. If I'm correct, you won't see an accurate performance comparison until you use the true loop length. If it really is a 4-step loop, then there really isn't enough computation there to significantly improve upon. You need to look at the rest of the code for opportunities for speed-up.