How to calculate the pairwise distince between two dataset without any loop
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Edward
am 7 Feb. 2021
Kommentiert: Edward
am 16 Feb. 2021
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 Kommentare
Image Analyst
am 7 Feb. 2021
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.
Akzeptierte Antwort
Bruno Luong
am 7 Feb. 2021
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 Kommentare
Bruno Luong
am 16 Feb. 2021
Bearbeitet: Bruno Luong
am 16 Feb. 2021
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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Calculus finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!