How to calculate the pairwise distince between two dataset without any loop
조회 수: 1 (최근 30일)
이전 댓글 표시
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
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.
채택된 답변
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
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Calculus에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!