MATLAB Vectorization: Eliminating For Loops

Vectorized MATLAB code runs 10-100x faster than loop-based equivalents. Here's how to think in vectors.

Key Insights

  • MATLAB is optimized for matrix operations — loops fight against the language design
  • logical indexing replaces most conditional loops
  • bsxfun and implicit expansion handle broadcasting automatically

Loop vs Vectorized

% Slow: element-wise loop
result = zeros(size(data));
for i = 1:length(data)
    result(i) = data(i)^2 + 2*data(i) + 1;
end

% Fast: vectorized
result = data.^2 + 2*data + 1;

Logical Indexing

% Replace values below threshold
data(data < 0) = 0;

% Extract matching elements
valid = measurements(measurements > lower & measurements < upper);

Broadcasting with Implicit Expansion

% Subtract column means from each row
centered = data - mean(data, 1);  % automatic expansion

Liked this? There's more.

Every week: one practical technique, explained simply, with code you can use immediately.