MATLAB – Calculate L2 Euclidean distance

Here’s how to calculate the L2 Euclidean distance between points in MATLAB.

The whole kicker is you can simply use the built-in MATLAB function, pdist2(p1, p2, ‘euclidean’) and be done with it. p1 is a matrix of points and p2 is another matrix of points (or they can be a single point).

However, initially I wasn’t really clear about what was going on. So if you are still a bit confused, let’s chat about it…

The scenario: You have one point, aPoint, that you wish to compare against a bunch of other points bunchOfPoints. For simplicity, let’s work in two-dimensional (2D) space. Note that 2D means each point is composed of two pieces of information (i.e. has 2 components).

We start by defining our points, then we calculate the L2 distance by hand, then we use the built-in pdist2() function to show we get the same result. And then finally, as a little bonus, we show how to get the minimum L2 Euclidean distance at the end.

Here’s how to calculate the equation by hand if you’re interested.

% disL2
% Define our points.
aPoint = [1,4]; % A single point with 2 components.
bunchOfPoints = [2,3; 1,4; 0,1]; % A bunch of other points.
% Make 'aPoint' the same size as a 'bunchOfPoints'.
aPointMatrix = repmat(aPoint,size(bunchOfPoints,1),1);
% Calculate by hand.
%% L2 Euclidean Norm.
% 1) Take the difference between the two -> aPointMatrix-bunchOfPoints
% 2) Square the difference to get rid of positive/negative: 
%       (aPointMatrix-bunchOfPoints).^2
% 3) Sum this up along the rows.
%       (sum(((aPointMatrix-bunchOfPoints).^2), 2))
% 4) Take the square root of this.
%       (sum(((aPointMatrix-bunchOfPoints).^2), 2)).^0.5
pointsDifSquare = (sum(((aPointMatrix-bunchOfPoints).^2), 2)).^0.5
% output = 1.4142 0 3.1623
%% Or we can just use this handy built-in function...
d = pdist2(aPoint,bunchOfPoints,'euclidean') 
% same output! = 1.4142 0 3.1623
%% Bonus, how to find the min distance!
[theMinDistance, indexOftheMinDistance] = min(d)
% Yeah! As expected theMinDistance = 0 and indexOftheMinDistance = 2.

Questions/comments? If you just want to say thanks, consider sharing this article or following me on Twitter!