MATLAB Answers

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

72 views (last 30 days)
Edward on 7 Feb 2021
Commented: Edward on 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 CommentsShowHide 1 older comment
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 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 CommentsShowHide 4 older comments
Edward on 16 Feb 2021
Thank you! Bruno.

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!