TExcelTAD
Home › MATLAB / Octave › Vectorization

Vectorization

Vectorization means writing operations on whole arrays instead of looping over elements. It's the most "MATLAB-like" way to write code: shorter, usually easier to read once you're used to it, and often much faster, because the built-in array operations run in optimised compiled code.

Loop vs vectorised

Compute the volume of 5 cylinders with given radii and heights:

matlab · try it yourself
r = [1 2 1.5 3 0.5];
h = [10 4 6 2 20];

% Loop version
V = zeros(size(r));
for k = 1:numel(r)
    V(k) = pi * r(k)^2 * h(k);
end
disp(V)

% Vectorised version: one line, same result
V2 = pi * r.^2 .* h;
disp(V2)
disp(isequal(V, V2))
   31.416   50.265   42.412   56.549   15.708
   31.416   50.265   42.412   56.549   15.708
1

The vectorised version reads like the formula itself. The key is the dotted operators .^ and .*, which apply element by element.

Replacing common loop patterns

Loop pattern Vectorised replacement
Sum / product of elements sum(v), prod(v)
Running total cumsum(v)
Count elements meeting a condition sum(v > t) or nnz(v > t)
Keep elements meeting a condition v(v > t)
Replace elements meeting a condition v(v < 0) = 0
Differences between neighbours diff(v)
Find first match find(cond, 1)
if/else per element Logical masks multiplied by values
matlab · try it yourself
v = [3 8 -2 7 -5 10];
fprintf('sum %d, positives %d, first negative at %d\n', sum(v), sum(v > 0), find(v < 0, 1));
disp(cumsum(v))
disp(diff(v))
clipped = v;
clipped(clipped < 0) = 0;
disp(clipped)
sum 21, positives 4, first negative at 3
    3   11    9   16   11   21
    5  -10    9  -12   15
    3    8    0    7    0   10

Vectorising if/else

A per-element if can be written with logical masks. A logical value acts as 1 or 0 in arithmetic, so multiplying by a mask "switches" parts of a formula on and off:

matlab · try it yourself
% Shipping cost: 4.99 for orders under 50, free from 50
orders = [12.00 49.99 50.00 120.00];

cost = 4.99 * (orders < 50);
disp(cost)

% Piecewise tax: 0% up to 1000, 20% of the part above 1000
income = [800 1000 1500 4000];
tax = 0.2 * max(income - 1000, 0);
disp(tax)
   4.9900   4.9900        0        0
     0     0   100   600

max(x, 0) (element-wise against a scalar) is a neat way to say "zero if negative".

Working with matrices

Vectorization extends to matrices. Functions operate along dimensions, and implicit expansion combines rows with columns:

matlab · try it yourself
% Rows = students, columns = 3 tests
marks = [70 85 90; 55 60 52; 88 94 79; 45 72 66];
weights = [0.25 0.25 0.5];

final = marks * weights';          % weighted average per student
disp(final')
passed = final >= 60;
fprintf('%d of %d students passed\n', sum(passed), numel(passed));

normalised = marks ./ max(marks);  % divide each column by its maximum
disp(round(normalised * 100))
   83.750   54.750   85.000   62.250
3 of 4 students passed
    80    90   100
    63    64    58
   100   100    88
    51    77    73

marks * weights' uses a matrix product to compute every student's weighted sum at once. marks ./ max(marks) divides each column by that column's maximum through implicit expansion.

When a loop is fine

Vectorization isn't a religion. Use a loop when:

  • each step depends on the previous result (a recurrence like x(k) = f(x(k-1))),
  • the vectorised version would build huge temporary arrays,
  • the loop is genuinely clearer to the reader.

Modern MATLAB and Octave run simple loops reasonably fast. Write the clear version first, and vectorise the parts that matter.

matlab · try it yourself
% A recurrence: each value depends on the previous one, so a loop is natural.
x = zeros(1, 6);
x(1) = 0.5;
for k = 2:6
    x(k) = 3.2 * x(k-1) * (1 - x(k-1));   % logistic map
end
fprintf('%.4f ', x);
fprintf('\n');
0.5000 0.8000 0.5120 0.7995 0.5129 0.7995 

Test yourself

Which line is a vectorised way to count the elements of v greater than 10?

  1. for k = v, if k > 10, n = n + 1; end, end
  2. sum(v > 10)
  3. count(v, 10)
  4. length(v) > 10

What does diff([2 5 9 10]) return?

  1. [3 4 1]
  2. [2 5 9 10]
  3. [7 5 1]
  4. 26

Which situation is hard to vectorise and suits a loop?

  1. Squaring every element
  2. Summing a column
  3. A recurrence where each value depends on the previous one
  4. Replacing negative values with zero