Since Matlab 6.5, published 12 years ago, loops are processed efficiently. Some functions can operate on a complete array and using loops to process the array element by element are slower. But when larger intermediate arrays are required, it depends on the problem, if loops or vectorized operations are faster.
So in general start with optimizing the loop before you compare the speed with a vectorized version:
- Omit repeated operations. Move such operations before the loop and store the result in a temporary variable.
- Pre-allocate vectors instead of letting them grow in each iteration.
- Reduce the number of calls of external functions.