How to calculate the pairwise distince between two dataset without any loop

1 回表示 (過去 30 日間)
Edward
Edward 2021 年 2 月 7 日
コメント済み: Edward 2021 年 2 月 16 日
I have two datasets, say, and , where m and n is the number of observations. if I want to calculate the following distinance:
where and , and . and is symmetric
--------------------------------------------------------------------------------------------------------------------------------
update:
for example:
X = [1 2 1;3 4 2;5 6 3]
Y = [5 6 1;7 8 2]
and the final results should be , where each element of Matrix C is calculated by
for example,
h = X(2, 1:2) - Y(1, 1:2);
u = X(2, 3) - Y(1, 3);
C(2,1) = (h-u)*inv(eye(2) + sigma*u^2))*(h-u)'
and I need to calculate the Matrix C
How can I implement this in a vectorized way (without any loops)?
Thanks!
  2 件のコメント
Image Analyst
Image Analyst 2021 年 2 月 7 日
Can you say it in English instead of mathematical jargon? And attach your "datasets" so we know what they really are.
Meanwhile the sum symbol is done by the sum() function, and the T transpose is done by the apostrophe symbol. The -1 can be done with inv(), so give it a try, like
h = X(i, 1:2) - Y(j, 1:2);
u = X(i, 3) - Y(j, 3);
distance = (h-u) * inv(I2 + sum(u.^2)) * (h-u)'
Or something like that.
Edward
Edward 2021 年 2 月 7 日
Hello!
Thanks for answering, I have updated the problem and make it more clear. Could you help me implement it without loop?

サインインしてコメントする。

採用された回答

Bruno Luong
Bruno Luong 2021 年 2 月 7 日
If you have latest MATLAB release (for pagemtimes) and download this Multiple same size solver FEX
X = [1 2 1;3 4 2;5 6 3]
Y = [5 6 1;7 8 2]
sigma = rand(2);
m = size(X,1);
n = size(Y,1);
XX = permute(X, [3 2 1 4]);
YY = permute(Y, [3 2 4 1]);
XmY = reshape(XX-YY,1,[],m*n);
h = XmY(:,1:2,:);
u = XmY(:,3,:);
hmu = h-u;
I2 = eye(2)
A = I2 + sigma.*(u.^2);
% https://www.mathworks.com/matlabcentral/fileexchange/24260-multiple-same-size-linear-solver?s_tid=srchtitle
C = SliceMultiSolver(A, permute(hmu,[2 1 3])); % WARNING: conjugate needed for complex?
C = pagemtimes(hmu, C);
C = reshape(C,[m n])
  5 件のコメント
Bruno Luong
Bruno Luong 2021 年 2 月 16 日
編集済み: Bruno Luong 2021 年 2 月 16 日
The bug is on my side I just edit it.
No I don't change anymore my code. I hate question that is modified. I don't have free time to support questions that are constantly modified.
And beside if you don't feel comfortable of maintaining the vectorizing code, then I strongly suggest you NOT using it.
Edward
Edward 2021 年 2 月 16 日
Thank you! Bruno.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCalculus についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by