<< Chapter < Page Chapter >> Page >
In MATLAB, one should always try to avoid using loops. This module introduce the concept of vectorization.

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 a n n , and b n 1000 n for n 1,...,1000 . Calculate n 1 1000 a n b n , and store in the variable 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 Recognizing that the sum is the inner product of the vectors a and b , a b T , we can do better: ssum = a*b' %Vectorized, better!

For more detailed information on vectorization, please take a look at MathWorks' Code Vectorization Guide .

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, An introduction to matlab. OpenStax CNX. Jan 20, 2006 Download for free at http://cnx.org/content/col10323/1.3
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'An introduction to matlab' conversation and receive update notifications?

Ask