Skip to content

Pairwise squared distances

Question

Implement squared Euclidean distances between rows of finite matrices A and B without creating a three-dimensional difference tensor. Address tiny negative round-off.

Short answer

Expand the squared norm into row norms and a matrix product. Floating-point cancellation can yield tiny negative values, which are clipped to zero. Large-magnitude nearly identical vectors may still need a more stable direct calculation.

Original question and answer written by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question

Start with a free lesson: Basic Statistics and Regression is part of a free topic. Create a free account, no card needed, to read it in full with worked solutions.

Read it free