I don't know whether this question fits best on StackOverflow, Math.SE or CrossValidated; I am looking for a practical algorithm to generate uniformly distributed matrices in $SO(n,\mathbb{R})$ (aka uniformly random rotation matrices in dimension $n$). This answer goes into rather lengthy explanations without giving a clear "recipe", and Wikipedia provides a description for which I am struggling to find an implementation:
Stewart (1980) replaced this with a more efficient idea that Diaconis & Shahshahani (1987) later generalized as the "subgroup algorithm" (in which form it works just as well for permutations and rotations). To generate an (n + 1) × (n + 1) orthogonal matrix, take an n × n one and a uniformly distributed unit vector of dimension n + 1. Construct a Householder reflection from the vector, then apply it to the smaller matrix (embedded in the larger size with a 1 at the bottom right corner).
As far as I understand, this would be equivalent to (but more efficient than) the following (Matlab language):
Q = randn(n); % uniformly random entries
Q = Q * diag(sign(diag(Q))); % flip column signs to have positive diagonal
Q = orth(Q); % orthogonalise
Q = Q / det(Q)^(1/n); % unit determinant
I am asking: i) whether the previous indeed generates uniformly distributed matrices in $SO(n)$; and ii) whether someone could provide a practical implementation of the algorithm described on Wikipedia (quoted above).