To show an example of vectorizing at work, consider writing an M-file that will clip an input signal to given upper and lower limits. The code from a conventional language would look like the following in MATLAB :
The problem with this first version is the doubly nestedfunction y = clip( x, lo, hi ) % CLIP --- threshold large and small elements in matrix x % ==========> SLOWEST POSSIBLE VERSION <================ % [M,N] = size(x); for m = 1:M for n = 1:N if x(m,n) > hi x(m,n) = hi; elseif x(m,n) < lo x(m,n) = lo; end, end, end
forwhich is used to traverse all the elements of the matrix. In order to make a faster version, we must drop the loop altogether and use the vector nature of logicals. Furthermore, we can exploit the fact that
FALSEhave numerical values to use them as masks (via multiplication) to select parts of the matrix
x. Note that
( [xSPM_lt;=hi] + [x>hi] ); is a matrix of all ones.
If you count the number of arithmetic operations done in the second version, you will find that it is much greater than the count for the first version. To see this, use a very large matrix forfunction y = clip( x, lo, hi ) % ============> FAST VERSION <============= % (uses matrix Logicals to replace Loops) y = (x .* [x<=hi]) + (hi .* [x>hi]); y = (y .* [x>=lo]) + (lo .* [x<lo]);
x, and time the two functions with
flops. Even though you can generate cases where the second version requires 10 times as many operations, it will still run much faster---maybe 10 times faster!