MATLAB Answers

Vectorization of Weighted Minkowski Distance

12 views (last 30 days)
I am trying to vectorize the code for this Weighted Minkowski Distance.
I am aware that in Matlab both pdist and pdist2 suffice the purpose when Theta is equal to either 1 or scalar:
Mat = theta*(squareform(pdist(X,'minkowski',p))) %for theta = scalar
However in my implementation, which follows, Theta is a vector with the same dimension as the number of columns of X.
X = [1:5; 2:6; 3:7]';
p=1.99;
n = length(X);
theta = [0.1 .7 .2];
tic
Mat = zeros(n,n);
for i=1:n
for j=i+1:n
Mat(i,j)=sum(theta.*abs(X(i,:)-X(j,:)).^p)^(1/p);
end
end
Mat = Mat+Mat'+eye(n);
toc
In order to vectorize this, I made the following attempt, but I believe there is something wrong, as the results do not match
col = size(X,2);
M1 = bsxfun(@minus,X(:), X(:).'); % square form
M2 = theta.*abs(reshape(M1.',[3 col*n*n]).');
M3 = sum((M2(1:10,:)).^p,2)^(1/p);
Mats=squareform(M3)+eye(n);
Any help will be highly appreciated.
Thank you.

Accepted Answer

Bruno Luong
Bruno Luong on 7 Apr 2021
[n,m] = size(X); % do not use length
Xi = reshape(X,[n,1,m]);
Xj = reshape(X,[1,n,m]);
tt = reshape(theta,[1,1,m]);
Mat2 = sum(tt.*abs(Xi-Xj).^p,3).^(1/p);
Mat2(1:n+1:end) = 1;
  2 Comments

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!