Calculating the correlation between two (or more) variables with matrices is essentially a two-step process:
- Build the covariance matrix Σ.
- Scale it by the variables’ standard deviations to get the correlation matrix R.
Below is the “recipe” in compact matrix form, followed by a mini walk-through.
- Organise your data
Suppose you have n observations of p variables.
Put the data in an n × p matrix X:
X = [ x₁₁ … x₁p
⋮ ⋱ ⋮
xₙ₁ … xₙp ]
Each column is a variable; each row is an observation.
- Mean-centre the data
Let μ be the 1 × p row vector of column means:
μ = (1/n) 1ᵀX (1ᵀ is an n-length row of ones)
Form the centred matrix:
X_c = X – 1 μ
- Compute the covariance matrix
Σ = (1/(n – 1)) X_cᵀ X_c (p × p)
Element Σ_{ij} is the sample covariance between variables i and j.
- Convert covariance to correlation
(a) Create D, the diagonal matrix of standard deviations:
D = diag(√Σ_{11}, √Σ_{22}, …, √Σ_{pp})
(b) Correlation matrix:
R = D^{-1} Σ D^{-1}
Each entry r_{ij} in R equals the usual Pearson correlation coefficient between variables i and j, i.e.
r_{ij} = Σ_{ij} / (σ_i σ_j)
Quick 2-variable example
Data (n = 4):
x: 2, 4, 6, 8
y: 1, 3, 5, 7
X = ⎡2 1⎤
⎢4 3⎥
⎢6 5⎥
⎣8 7⎦
-
μ = (5, 4)
-
X_c = X – 1μ = ⎡-3 -3⎤, ⎡-1 -1⎤, ⎡1 1⎤, ⎡3 3⎤
-
Σ = (1/3) X_cᵀX_c = ⎡10 10⎤
⎣10 10⎦
So σ_x = σ_y = √10.
-
R = D^{-1}ΣD^{-1} = (1/√10) Σ (1/√10) = ⎡1 1⎤
⎣1 1⎦
The off-diagonal element r_{xy} = 1, meaning perfect positive correlation—exactly what we expect because y is a linear function of x here.
That’s all there is to computing correlation with matrices: centre → covariance → scale.