MATLAB for Engineering Problem Solving
Vectorization and Performance
Writing Faster MATLAB Code
MATLAB's power comes from its name: MATrix LABoratory. It's built to work with arrays and matrices. Writing efficient code means shifting your thinking from operating on one number at a time to operating on whole arrays at once. This is the core of vectorization, and it's the key to unlocking significant performance gains, especially with large datasets.
Procedural code tells MATLAB how to do something step-by-step. Vectorized code tells MATLAB what to do, and lets its highly optimized engine figure out the fastest way to do it.
Let's start with one of the most common performance traps: growing arrays inside a loop. Every time you append an element to an array, MATLAB has to find a new, larger block of memory and copy all the existing data over. For large loops, this is incredibly slow.
%% The SLOW way: Growing an array
clearvars;
tic; % Start timer
n = 50000;
result = []; % Initialize an empty array
for i = 1:n
result(i) = i^2; % Array grows in each iteration
end
toc; % Stop timer
The solution is to preallocate. You tell MATLAB the final size of the array before the loop starts. This way, MATLAB reserves the full memory block just once.
%% The FAST way: Preallocation
clearvars;
tic; % Start timer
n = 50000;
result = zeros(1, n); % Preallocate memory
for i = 1:n
result(i) = i^2; % Fill the existing slots
end
toc; % Stop timer
Running these two snippets shows a dramatic difference in speed. Preallocation is a simple habit that pays huge dividends.
In Matlab, one of the most effective methods to boost code efficiency is to preallocate memory for arrays.
Thinking in Vectors
Preallocation fixes the memory issue, but we can often eliminate the loop entirely. This is vectorization: replacing explicit loops with array expressions. Instead of calculating the square of each number one by one, we can tell MATLAB to square the entire vector.
%% The VECTORIZED way: No loops
clearvars;
tic;
n = 50000;
vals = 1:n; % Create a vector from 1 to n
result = vals.^2; % Square every element at once
toc;
This is not just cleaner code; it's much faster. MATLAB's built-in functions are written in low-level languages like C or Fortran and are heavily optimized for these kinds of bulk operations. Your goal should be to leverage them whenever possible.
A powerful vectorization technique is logical indexing. Instead of looping through an array to find elements that meet a condition, you can create a logical 'mask'—an array of true and false values—and use it to access or modify elements directly.
Suppose we want to replace all negative values in a dataset with zero.
data = [5, -2, 8, -1, 0, 9, -4];
% Create a logical mask
negativeMask = data < 0;
% The mask is: [false, true, false, true, false, false, true]
% Use the mask to change only the negative values
data(negativeMask) = 0;
% The final data is: [5, 0, 8, 0, 0, 9, 0]
This is far more efficient and readable than writing a for loop with an if statement inside it.
Finding Bottlenecks
How do you find the slow parts of a complex script? Guessing is not a strategy. MATLAB provides a built-in tool called the Profiler to analyze your code's performance.
To use it, you open the tool, run your code, and it generates a detailed report. The report shows how much time was spent on each line of code, highlighting the bottlenecks. It will often point directly to loops that could be vectorized or arrays that are being resized dynamically.
To start the profiler, simply type
profile onin the command window, run your script, and then typeprofile viewerto see the results.
Related to vectorization is a concept called implicit expansion. This allows you to perform operations on arrays of different sizes without explicitly reshaping them, as long as their dimensions are compatible. For instance, you can add a row vector to a matrix. MATLAB will virtually expand the vector to match the number of rows in the matrix and perform the addition element-wise.
% A 3x3 matrix
A = [1, 2, 3;
4, 5, 6;
7, 8, 9];
% A 1x3 row vector
b = [10, 20, 30];
% Add b to every row of A
C = A + b;
Behind the scenes, MATLAB treats b as if it were a 3x3 matrix where each row is [10, 20, 30]. This avoids the need for manual array replication and simplifies your code.
By embracing preallocation, vectorization, and tools like the Profiler, you can transform slow, procedural scripts into high-performance tools ready for serious engineering and data analysis tasks.