Computing Mahalanobis Distance Between Set of Points and Set of Reference Points

조회 수: 2 (최근 30일)
Hello,
I have an n x p matrix - mX which is composed of n points in R^p.
I have another m x p matrix - mY which is composed of m reference points in R^p.
I would like to create an n x m matrix - mD which is the Mahalanobis Distance matrix.
D(i, j) means the Mahalanobis Distance between point j in mX, mX(j, :) and point i in mY, mY(i, :).
Namely, is computes the following:
mD(i, j) = (mX(j, :) - mY(i, :)) * inv(mC) * (mX(j, :) - mY(i, :)).';
Where mC is the given Mahalanobis Distance PSD Matrix.
It is easy to be done in a loop, is there a way to vectorize it?
Namely, is the a function which its inputs are mX, mY and mC and its output is mD and fully vectorized without using any MATLAB toolbox?
Thank You.

채택된 답변

Royi Avital
Royi Avital 2015년 8월 15일
편집: Royi Avital 2015년 8월 15일
Here is the solution fully vectorized (Though uses much more multiplications than needed):
mA = reshape(bsxfun(@minus, permute(mY, [1, 3, 2]), permute(mX, [3, 1, 2])), [(m * n), p]);
mD = reshape(diag(A* inv(mC) * A.'), [m, n]);
If anyone has faster way (Not necessarily fully vectorized) I'd be happy to see.
Thank You.

추가 답변 (1개)

Image Analyst
Image Analyst 2015년 8월 9일
Use *mahal(* ) in the Statistics and Machine Learning Toolbox. I haven't used it yet so I don't have any demo for you. Why do you need it?
  댓글 수: 2
Royi Avital
Royi Avital 2015년 8월 9일
Hi, First I would like a solution without any toolbox as I noted above. Second, the function you suggested doesn't allow predefined weighting PSD Matrix (It infers it from the data). There's also `pdist`, yet I want to be toolboxes independent. Thank You.
Image Analyst
Image Analyst 2015년 8월 9일
What's m, n, and p? Your code is already at least partially vectorized. If m, n, and p are less than a few million, then it probably won't take much time at all even if it's not vectorized.

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by