How to write code the Chebyshev and Mahalanobis distance using bsxfun function?

18 views (last 30 days)
Hi, I found the sample code to calculate distance of two matrix using euclidean distance from here: https://stackoverflow.com/questions/27475978/finding-k-nearest-neighbors-and-its-implementation The data matrix are as below:
load fisheriris
X = meas(:,3:4);
newpoints = [5 1.45; 7 2; 4 2.5; 2 3.5];
How i'm going to apply the Chebyshev and Mahalanobis distance and replace the function below:
%// Use Euclidean
dists = sqrt(sum(bsxfun(@minus, x, newpoint).^2, 2));
I tried to change the code as :
dists = max(abs(bsxfun(@minus, X, newpoint)))
The answer is as below. May be because i put the max function based on the formula.
dists2 =
4.0000 1.3500
But, if i used this knnsearch code, it is work as expected. But i need to apply the bsxfun so that my code will be standardized with the upper codes. I want to compare the different distances in my algorithm:
[ncb,dcb] = knnsearch(X,newpoint,'k',10,'distance','chebychev')
Appreciate if anyone could help me.

Accepted Answer

Julian Hapke
Julian Hapke on 8 Mar 2018
Hi,
your example code does not work. Bsxfun cannot operate on those arrays. When X (as in your case) is an Nx2 matrix, and you want to calculate the distance of every new point (no matter what distance) in
newpoints
you need to permute it into a 1x2xM matrix, with M being the number of new points.
In the line to calculate the Chebyshev distance, you used the max command wrong, because what you need is the maximum of the distances in each dimension (as far as I understand the definition of that distance correctly). Have a look at
doc max
to see what i mean.
So this is what I came up with:
load fisheriris
oldpoints = meas(:,3:4);
newpoints = [5 1.45; 7 2; 4 2.5; 2 3.5];
newpoints = permute(newpoints, [3,2,1]);
% Euclidean distance
dists_euclid = sqrt(sum(bsxfun(@minus, newpoints, oldpoints).^2, 2));
% Chebyshev distance
dists_cheby = max(abs(bsxfun(@minus, oldpoints, newpoints)),[],2);
after that you can use the command
squeeze
or (better)
permute
to get a two dimensional array again (might be easier to handle) and do the sorting stuff.
Hope this helps!

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!