Programming Tips

MATLAB is an interpreted language, and its calculation speed is relatively slow. Therefore, how to improve the program's running speed during programming is an important consideration. This section mainly introduces two methods to increase program speed: vectorization and pre-allocating memory space.

Vectorization

One method to make programs run faster is to vectorize the algorithms that construct the program. Where other programming languages might use for loops or do loops, MATLAB can use vector or matrix operations.

[Example 3-28] For the following program:

code.matlab
x = .01;
for k = 1:1001
    y(k) = log10(x);
    x = x + .01;
end

After vectorization, it looks like this:

code.matlab
x = .01:.01:10;
y = log10(x);

However, for complex code, the effect of vectorization is not always obvious.

Pre-allocating Memory Space

If you cannot vectorize a certain piece of code, you can speed up for loops by pre-allocating the memory space for any vector or array that will hold the output.

[Example 3-29] The code below uses the zeros function to pre-allocate memory space for the vector created in the for loop, making the for loop run significantly faster.

code.matlab
r = zeros(32, 1);
for n = 1:32
    r(n) = rank(magic(n));
end

The previous example did not use memory pre-allocation. Each time the loop ran, the MATLAB interpreter would increase the elements of the r vector by one. After pre-allocating memory, this step is eliminated, thereby accelerating the program's execution.