MATLAB 距離計算
2017-01-16 by:CAE仿真在線 來源:互聯(lián)網(wǎng)
判別分析時,通常涉及到計算兩個樣本之間的距離,多元統(tǒng)計學(xué)理論中有多種距離計算公式。MATLAB中已有對應(yīng)函數(shù),可方便直接調(diào)用計算。距離函數(shù)有:pdist, pdist2, mahal, squareform, mdscale, cmdscale
主要介紹pdist2 ,其它可參考matlab help
D = pdist2(X,Y)
D = pdist2(X,Y,distance)
D = pdist2(X,Y,'minkowski',P)
D = pdist2(X,Y,'mahalanobis',C)
D = pdist2(X,Y,distance,'Smallest',K)
D = pdist2(X,Y,distance,'Largest',K)
[D,I] = pdist2(X,Y,distance,'Smallest',K)
[D,I] = pdist2(X,Y,distance,'Largest',K)
練習(xí):
2種計算方式,一種直接利用pdist計算,另一種按公式(見最后理論)直接計算。
% distance
clc;clear;
x = rand(4,3)
y = rand(1,3)
for i =1:size(x,1)
for j
=1:size(y,1)
a = x(i,:); b=y(j,:);
%
Euclidean distance
d1(i,j)=sqrt((a-b)*(a-b)');
%
Standardized Euclidean distance
V = diag(1./std(x).^2);
d2(i,j)=sqrt((a-b)*V*(a-b)');
%
Mahalanobis distance
C = cov(x);
d3(i,j)=sqrt((a-b)*pinv(C)*(a-b)');
%
City block metric
d4(i,j)=sum(abs(a-b));
%
Minkowski metric
p=3;
d5(i,j)=(sum(abs(a-b).^p))^(1/p);
%
Chebychev distance
d6(i,j)=max(abs(a-b));
%
Cosine distance
d7(i,j)=1-(a*b')/sqrt(a*a'*b*b');
%
Correlation distance
ac = a-mean(a); bc =
b-mean(b);
d8(i,j)=1- ac*bc'/(sqrt(sum(ac.^2))*sqrt(sum(bc.^2)));
end
end
md1 = pdist2(x,y,'Euclidean');
md2 = pdist2(x,y,'seuclidean');
md3 = pdist2(x,y,'mahalanobis');
md4 = pdist2(x,y,'cityblock');
md5 = pdist2(x,y,'minkowski',p);
md6 = pdist2(x,y,'chebychev');
md7 = pdist2(x,y,'cosine');
md8 = pdist2(x,y,'correlation');
md9 = pdist2(x,y,'hamming');
md10 = pdist2(x,y,'jaccard');
md11 = pdist2(x,y,'spearman');
D1=[d1,md1],D2=[d2,md2],D3=[d3,md3]
D4=[d4,md4],D5=[d5,md5],D6=[d6,md6]
D7=[d7,md7],D8=[d8,md8]
md9,md10,md11
運(yùn)行結(jié)果如下:
x =
0.5225
0.6382
0.6837
0.3972
0.5454
0.2888
0.8135
0.0440
0.0690
0.6608
0.5943
0.8384
y =
0.5898 0.7848 0.4977
D1 =
0.2462
0.2462
0.3716
0.3716
0.8848
0.8848
0.3967
0.3967
D2 =
0.8355
0.8355
1.5003
1.5003
3.1915
3.1915
1.2483
1.2483
D3 =
439.5074 439.5074
437.5606 437.5606
438.3339 438.3339
437.2702 437.2702
D4 =
0.3999
0.3999
0.6410
0.6410
1.3934
1.3934
0.6021
0.6021
D5 =
0.2147
0.2147
0.3107
0.3107
0.7919
0.7919
0.3603
0.3603
D6 =
0.1860
0.1860
0.2395
0.2395
0.7409
0.7409
0.3406
0.3406
D7 =
0.0253
0.0253
0.0022
0.0022
0.3904
0.3904
0.0531
0.0531
D8 =
1.0731
1.0731
0.0066
0.0066
1.2308
1.2308
1.8954
1.8954
md9 =
1
1
1
1
md10 =
1
1
1
1
md11 =
1.5000
0.0000
1.5000
2.0000
基本理論公式如下:
相關(guān)標(biāo)簽搜索:MATLAB 距離計算 MatLab培訓(xùn) MatLab培訓(xùn)課程 MatLab在線視頻教程 MatLab技術(shù)學(xué)習(xí)教程 MatLab軟件教程 MatLab資料下載 MatLab代做 MatLab基礎(chǔ)知識 Fluent、CFX流體分析 HFSS電磁分析 Ansys培訓(xùn) Abaqus培訓(xùn)