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

3 views (last 30 days)
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 Comments
Image Analyst
Image Analyst on 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.
Edward
Edward on 7 Feb 2021
Hello!
Thanks for answering, I have updated the problem and make it more clear. Could you help me implement it without loop?

Sign in to comment.

Accepted Answer

Bruno Luong
Bruno Luong on 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 Comments
Bruno Luong
Bruno Luong on 16 Feb 2021
Edited: Bruno Luong on 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.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!