Vectorization of Weighted Minkowski Distance

2 次查看(过去 30 天)
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.

采纳的回答

Bruno Luong
Bruno Luong 2021-4-7
[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 个评论
Bruno Luong
Bruno Luong 2021-4-7
If your MATLAB doesn't support auto expansion you need to replace
Mat2 = sum(tt.*abs(Xi-Xj).^p,3).^(1/p)
by two ugly bsxfun statements.

请先登录,再进行评论。

更多回答(0 个)

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by