next up previous contents
Next: The COLON Operator Up: Vectorize Previous: Vector Logicals

Vectorize a CLIP function

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 :

 function  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
The problem with this first version is the doubly nested for which 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 TRUE and FALSE have 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.
 function  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]);
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 for x, and time the two functions with etime and 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!



William Simcoe
Tue Apr 15 18:51:39 EDT 1997