An matrix
is orthogonal if
. The set of all
orthogonal matrices is a compact group written as
. The uniform distribution on
is called Haar measure. There are many ways to generate random matrices for Haar measure. One of which is based on the Gram-Schmidt algorithm.
Proposition. Let be a
matrix such that each entry
is an independent standard normal random variable. Let
be the columns of
and let
be the result of applying Gram-Schmidt to
. Then the matrix
is distributed according to Haar measure.
Another way of stating the above proposition is that if has i.i.d. standard normal entries, and
is a QR-factorization of
calculated using Gram-Schmidt, then
is distributed according to Haar measure. However, most numerical libraries do not use Gram-Schmidt to calculate the QR-factorization of a matrix. This means that if you generate a random
and then use your computer’s QR-factorization function, then the result might not be Haar distributed as the plot below shows.

Fortunately there is a fix described in [1]! We can first use any QR-factorization algorithm to produce with
. We then compute a diagonal matrix
with
. Then, the matrix
is Haar distributed. The following python code thus samples a Haar distributed matrix in
.
import numpy as np
def sample_M(n):
M = np.random.randn(n, n)
Q, R = np.linalg.qr(M)
L = np.sign(np.diag(R))
return Q*L[None,:]
References
[1] Mezzadri, Francesco. “How to generate random matrices from the classical compact groups.” arXiv preprint math-ph/0609050 (2006). https://arxiv.org/abs/math-ph/0609050
I recently gave a talk at the Stanford student probability seminar on Haar distributed random matrices. My notes and many further references are available here.
One thought on “Uniformly sampling orthogonal matrices”