Step-by-Step Explanation and Answer: How to Vectorize MATLAB Code for Faster Execution
Vectorizing MATLAB code involves replacing loops with array operations to leverage MATLAB’s optimized built-in functions. Here’s a structured approach:
1. Identify Element-Wise Operations
- Scenario: Loops that perform operations on each element of an array/matrix.
- Vectorization: Use MATLAB’s element-wise operators (e.g.,
.*
,./
,.^
). - Example:
% Loop-based for i = 1:n y(i) = x(i)^2 + 3*x(i); end % Vectorized y = x.^2 + 3*x;
2. Replace Conditional Logic with Logical Indexing
- Scenario: Conditional checks inside loops.
- Vectorization: Use logical indexing to apply conditions to entire arrays.
- Example:
% Loop-based for i = 1:n if A(i) > 5 A(i) = 10; end end % Vectorized A(A > 5) = 10;
3. Use Built-In Functions for Aggregation
- Scenario: Summing, averaging, or applying cumulative operations.
- Vectorization: Replace loops with functions like
sum()
,mean()
,cumsum()
, orcumprod()
. - Example:
% Loop-based sum total = 0; for i = 1:n total = total + x(i); end % Vectorized total = sum(x);
4. Exploit Matrix Operations for Linear Algebra
- Scenario: Nested loops for matrix multiplications or transformations.
- Vectorization: Use MATLAB’s matrix operators (
*
,\
,'
, etc.). - Example:
% Loop-based matrix multiplication for i = 1:n for j = 1:m C(i,j) = A(i,:) * B(:,j); end end % Vectorized C = A * B;
5. Leverage Implicit Expansion for Array Broadcasting
- Scenario: Operations between arrays of different sizes (post-R2016b).
- Vectorization: Use implicit expansion instead of
repmat()
. - Example:
% Adding a column vector to a row vector result = col_vector + row_vector; % Automatically expands
6. Reshape Arrays to Avoid Loops
- Scenario: Multi-dimensional data processing.
- Vectorization: Use
reshape()
orpermute()
to align dimensions. - Example:
% Process 3D data without loops data_3D = reshape(data_1D, [dim1, dim2, dim3]);
7. Avoid Iterative Functions Like arrayfun
or cellfun
- Scenario: Applying functions to each element of an array/cell.
- Vectorization: Use native MATLAB operations unless the function is inherently scalar.
- Example:
% Avoid unless necessary processed = arrayfun(@myfunc, A); % Prefer vectorized alternatives processed = myfunc(A);
8. Preallocate Memory for Large Arrays
- Scenario: Even in vectorized code, preallocate output arrays to avoid dynamic resizing.
- Example:
% Preallocate result = zeros(size(A)); % Vectorized operation result = A .* B;
9. Profile and Optimize
- Use
tic
/toc
or MATLAB’s Profiler (profile viewer
) to compare loop-based vs. vectorized code. - Example:
tic; % Vectorized code toc;
10. Example: Vectorizing a Nested Loop
Task: Compute pairwise Euclidean distances between points in matrices X
(n×d) and Y
(m×d).
- Loop-Based:
D = zeros(n, m); for i = 1:n for j = 1:m D(i,j) = sqrt(sum((X(i,:) - Y(j,:)).^2)); end end
- Vectorized:
XX = sum(X.^2, 2); YY = sum(Y.^2, 2); XY = X * Y'; D = sqrt(XX + YY' - 2*XY); % Implicit expansion for efficient computation
Key Takeaways
- Why Vectorize?: MATLAB executes vectorized code faster due to internal optimizations (e.g., using precompiled C libraries).
- When to Use Loops: For non-vectorizable operations (e.g., recursive dependencies), MATLAB’s JIT compiler can optimize simple loops.
- Tools: Use functions like
bsxfun
(for older MATLAB versions),repmat
, and logical indexing to eliminate loops.
Final Code Example
% Replace a loop with logical indexing and vector math A = randi(10, 1, 1000); % Original array % Loop-based (slow) for i = 1:1000 if A(i) > 5 B(i) = A(i) * 2; else B(i) = A(i); end end % Vectorized (fast) B = A; B(A > 5) = A(A > 5) * 2;
By following these steps, you can systematically convert loop-heavy MATLAB code into efficient, vectorized operations, significantly improving execution speed.