Zetland
Zetland

Reputation: 567

What is the simplest way of finding the distance between two pixels?

This is maybe a bit of a noobish question - but say I want to find the distance between two pixels with coordinates (x1,y1) and (x2,y2). What would be the simplest way of doing this with MatLab?

Upvotes: 2

Views: 173

Answers (2)

rayryeng
rayryeng

Reputation: 104464

pdist is an OK answer, but I would argue that it's slow (at least for a larger amount of points). Also, pdist requires the statistics toolbox, so if you don't have that toolbox, you can't use that answer.

I would suggest using bsxfun combined with permute and reshape instead for a toolbox independent solution. Assume that X is a 2 column matrix that is arranged in the following way:

X = [x y];

x and y are the X and Y coordinates of all of your points you want to find the distances to. Therefore, each row consists of a single query point:

X2 = permute(X, [3 2 1]);
out = sqrt(sum(bsxfun(@minus, X, X2).^2, 2));
out = reshape(out, size(X,1), []);

This should give you the same output as applying squareform to the output of pdist. Specifically, at element (i,j) of out, this will give you the distance between point i and point j and so the diagonal elements should give values of 0 as self-distances are 0.

Suggestion by Jonas

We can avoid reshape which may be costly by replacing it with another permute call if we slightly change the way we permute the dimensions before calculating the distances:

out = sqrt(sum(bsxfun(@minus, permute(X, [1 3 2]), permute(X, [3 1 2])).^2, 3));

Upvotes: 5

Toygan
Toygan

Reputation: 422

X = [x1,y1;x2,y2];
d = pdist(X,'euclidean')

d is distance.

Upvotes: 3

Related Questions