Summary: In MATLAB, one should always try to avoid using loops. This module introduce the concept of vectorization.
Note: Your browser may not currently support MathML. See our browser support page for additional details. You can always view the correct math in the PDF version.
In MATLAB one should try to avoid loops. This can be done by vectorizing your code. The idea is that MATLAB is very fast on vector and matrix operations and correspondingly slow with loops. We illustrate this by an example.
Given
ssum.
Solution: It might be tempting to implement the above calculation as
a = 1:1000;
b = 1000 - a;
ssum=0;
for n=1:1000 %poor style...
ssum = ssum +a(n)*b(n);
end
ssum = a*b' %Vectorized, better!
For more detailed information on vectorization, please take a look at MathWorks' Code Vectorization Guide.