Introduction

Matlab Logo One of the main advantages of Matlab are vectorized functions, which are functions that can be performed on an entire array as if the function was applied to every individual element within the array. In low-level programming languages, the best way to perform an operation across an entire array is to use a FOR loop. In Matlab, the use of vectorized functions allow you to do the same thing without using FOR loops. For people who have experience with traditional programming languages like java and C++, vectorization may not come naturally. This tutorial will explain the advantages of using vectorized code and will provide some examples.

Why Use Vectorized Code?

Advantages

  • Increased Speed: Vectorized code runs significantly faster. How much faster? This depends on the commands used and the application. And although Matlab has made great strides in accelerating low-level code, vectorized code still runs faster. But in general, vectorized code is faster than it’s low-level counterpart.

  • Compact: Vectorized code is more compact and can be easier to read and understand.

Disadvantages

  • Difficulty: Most people with programming experience are used to doing things in a low-level manner (i.e. FOR loops). Vectorizing code can be a challenge because of the different thinking that is required. In addition, there is no set formula on how to vectorize code. A good working knowledge of the available functions within Matlab is certainly helpful when it comes to vectorization.

  • Compact: Being compact is both a blessing and a curse. Vectorized code can be difficult to understand because it is so compact. If the code is undocumented and does not have any comments, it can be a real pain to figure what the code does.

Two Simple Examples of Vectorizing Code

  1. Let’s say that I wanted to square all the elements within an array. If I wanted to do it the low-level method, I would use the following code in Matlab.

    x = [ 1 2 3 4 5 ];    % vector of values to square
    y = zeros(size(x));  % initialize new vector
    for i = 1 : length(x) % for each index
    y(i) = x(i)^2;         % square the value
    end                      % end of loop

    Conversely, I can do the same thing with vectorized code.

    x = [ 1 2 3 4 5 ]; % vector of values to square
    y = x.^2; % square all the values (notice the dot before the operator!)

    I think we can all agree that the second method is much easier! Lets look at the next example.

  2. Lets say we want to multiply two arrays together, element by element. So for example, if we have the following two arrays:

    a = [1 2 3];
    b = [6 5 4];

    we want to multiply it so that we get:

    c =[6 10 12];

    We can use the following code to accomplish that instead of using a FOR loop:

    c = a.*b; %once again, notice the dot before the *

An Example of the Speed Increase using Vectorized Code

Let’s compare the time it takes to process the following two snippets of code. The first is the non-vectorized version.

myVector = 1:100000; %row vector that goes from 1 to 100000
for x=1:length(myVector)
    if(mod(myVector(x),2))  %if the element is even
        myVector(x) = cot(myVector(x)); %we take the cotangent of it
    end
end

The second version is the vectorized code

myVector = 1:100000; %row vector that goes from 1 to 100000
indexTrue = mod(myVector,2)==1; %get the indices of elements that are even
myVector(indexTrue) = cot(myVector(indexTrue)); %take the cot of even elements

Using the profile command, we can do a quick time analysis on how long each snippet of code took to run. As it turns out, non-vectorized code ran in about 1.2 seconds. The vectorized code ran in about 0.03 seconds. This makes the vectorized version run 40 times as fast! As can be seen, there can be quite a dramatic speed improvement!

More Examples of Vectorized Code

  1. Given a vector, we want to add 10 to each element that has a value greater than 5. Here’s how it would be done using a low-level method:

    myVector = 1:10; %row vector that goes from 1 to 10
    for x=1:length(myVector)
        if(myVector(x) > 5)  %if the element is greater than 5
            myVector(x) = myVector(x) + 10; %we add 10 to it
        end
    end

    Here is the vectorized equivalent:

    %use logical indexing to figure out which elements are greater than five
    logicalIndex = myVector > 5;
    %add 10 to the elements greater than 5
    myVector(logicalIndex) = myVector(logicalIndex) + 10;
  2. Given a 4×4 matrix, we want to cube each element and then sum up all of the elements within the matrix. The following vectorized code can accomplish that.

    myMatrix = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16];
    total = sum(myMatrix.^3);
  3. Given a vector of data, we want to normalize the data to the largest data point. The following vectorized code can accomplish that.

    myVector = [3 4 5 1 4 6 3 4 1 10 8 9]; %example vector
    maxValue = max(myVector) %first get the largest value in the vector
     
    % divide the example vector by the max value to normalize
    normalizedData = myVector/maxValue
  4. Given a set of 3d data points, we want to find the average distance from the origin for each 3d point. The following vectorized code can accomplish that.

    xVector = [1 2 3 4 5];
    yVector = [3 4 5 6 1];
    zVector = [4 5 -3 2 1];
    distanceVector = sqrt(xVector.^2 + yVector.^2 + zVector.^2);
    averageDistance = avg(distanceVector);

Helpful Functions for Vectorization

Most of the standard functions are vectorized, but there is no clear cut recipe on how to go about vectorizing code. You will certainly get better at it with practice.

  1. arithmetic operators: +, - , .* (array multiply), ./ (array divide), .^ (array power), etc

  2. relational operators: ==, >, <, etc

  3. logical operators: & (and), | (or) , ~ (not), etc

  4. trigonometric functions: sin, cos, tan, asin, and so on.

  5. Other helpful functions: find, sort, abs, and many more.

Parting Note

Although vectorization can make your code simpler at times, it can also make your code archaic and difficult to understand. In addition, it can be difficult to vectorize your code at times, so it may not be worth the time and effort to do so. Thus, you may be wondering if it is really worth your time to vectorize your code. If you find it too difficult to vectorize your code, you may be better off just using a low level method. The most important thing is to make sure that your code works! After you get your code working, you can consider optimizing it through vectorization.

In conclusion, vectorization is not required, but it can certainly be beneficial. Unless the arrays you are dealing with are quite large (and depending on the operations performed), it can be difficult to see the benefits of vectorization. But in general, I believe that it’s good practice to get into the habit of using vectorized code as it is more efficient.

You can visit this link for a more in depth look on vectorization.

This is the end of the tutorial.