MATLAB 距离计算
2017-01-16 by:CAE仿真在线 来源:互联网
判别分析时,通常涉及到计算两个样本之间的距离,多元统计学理论中有多种距离计算公式。MATLAB中已有对应函数,可方便直接调用计算。距离函数有: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)
练习:
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
运行结果如下:
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
基本理论公式如下:
相关标签搜索:MATLAB 距离计算 MatLab培训 MatLab培训课程 MatLab在线视频教程 MatLab技术学习教程 MatLab软件教程 MatLab资料下载 MatLab代做 MatLab基础知识 Fluent、CFX流体分析 HFSS电磁分析 Ansys培训 Abaqus培训