Pairwise distance matrix

Suppose $x_1,\dots,x_n \in \mathbb{R}^d$. Is there a vectorized way of representing the square distance matrix $D_{ij} = \lVert x_i - x_j \rVert^2$?

• Nothing elegant, I'm afraid. The best I know is the first code block of this answer. – user357151 Apr 18 '17 at 19:08

We could make use of $$\|x_i-x_j\|^2=\|x_i\|^2+\|x_j\|^2-2(x_i \cdot x_j)$$, the Gramian matrix $$G=[\langle x_i, x_j\rangle]$$, its diagonal elements vector $$g=\operatorname{diag}(G)$$, and the vector of all ones $$\mathbf{1}$$ to write $$D = g\mathbf{1}^T + \mathbf{1}g^T - 2G.$$