【數據挖掘】MATLAB實現歐氏距離計算

歐氏距離的MATLAB實現


問題描述

實現任意給定兩個相同維度的向量之間的歐氏距離計算函數dist_E(x,y)。
測試代碼:x=[1,3,0,2]; y=[2,3,2,0]; dist=dist_E(x,y);

代碼實現

實現程序如下圖所示:

% 方法1
function dist = dist_E(x,y)
dist = [];
if(length(x)~=length(y))
    disp('length of input vectors must agree')  % disp函數會直接將內容輸出在Matlab命令窗口中
else
    z =(x-y).*(x-y);
    dist = sqrt(sum(z));
end
end

% 方法2:公式法
function dist = dist_E(x,y)
[m,n] = size(x);
dist = 0;
for i=1:max(m,n)
    dist = dist+(x(i)-y(i))^2;
end
dist = sqrt(dist);
end

% 方法3:採用pdist函數
function dist = dist_E(x,y)
dist = [x;y];
dist = pdist(dist); % 計算各行向量之間的歐式距離
end

命令行窗口輸入如下代碼:

x=[1,3,0,2]; 
y=[2,3,2,0];  
dist=dist_E(x,y)

代碼執行結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章