马氏距离在MATLAB中的代码,用代码表示公式.公式如图.i:第几列 k:层数 L:列数 D:两样本之间的距离 x:变量
来源:学生作业帮助网 编辑:作业帮 时间:2024/06/24 15:52:54
![马氏距离在MATLAB中的代码,用代码表示公式.公式如图.i:第几列 k:层数 L:列数 D:两样本之间的距离 x:变量](/uploads/image/z/3473694-54-4.jpg?t=%E9%A9%AC%E6%B0%8F%E8%B7%9D%E7%A6%BB%E5%9C%A8MATLAB%E4%B8%AD%E7%9A%84%E4%BB%A3%E7%A0%81%2C%E7%94%A8%E4%BB%A3%E7%A0%81%E8%A1%A8%E7%A4%BA%E5%85%AC%E5%BC%8F.%E5%85%AC%E5%BC%8F%E5%A6%82%E5%9B%BE.i%EF%BC%9A%E7%AC%AC%E5%87%A0%E5%88%97+k%EF%BC%9A%E5%B1%82%E6%95%B0+L%EF%BC%9A%E5%88%97%E6%95%B0+D%EF%BC%9A%E4%B8%A4%E6%A0%B7%E6%9C%AC%E4%B9%8B%E9%97%B4%E7%9A%84%E8%B7%9D%E7%A6%BB+x%3A%E5%8F%98%E9%87%8F)
马氏距离在MATLAB中的代码,用代码表示公式.公式如图.i:第几列 k:层数 L:列数 D:两样本之间的距离 x:变量
马氏距离在MATLAB中的代码,用代码表示公式.公式如图.
i:第几列 k:层数 L:列数 D:两样本之间的距离 x:变量
马氏距离在MATLAB中的代码,用代码表示公式.公式如图.i:第几列 k:层数 L:列数 D:两样本之间的距离 x:变量
function d = mahalanobis(X, Mu, C)
%MAHALANOBIS Mahalanobis distance.
% D = MAHALANOBIS(X, MU, C) returns the Mahalanobis distance between
% the length p vectors X and MU given the p by p covariance matrix
% C. If omitted, it is assumed that C is the identity matrix(单位矩阵/恒等矩阵)
% EYE(p). If either X or MU is an n by p matrix, D will be returned
% as an n by g matrix where n is the number of rows in X and g is
% the number of rows in MU where each entry i, j corresponds to the
% mahalanobis distance between row i of X and row j of MU. If MU is
% simply 0, it is treated as the origin from which Mahalanobis
% distance to X is calculated. C must be a positive, definite,
% symmetric matrix.
%
% The Mahalanobis distance between vectors X(i,:) and MU(j,:) is
% defined as:
%
% D(i,j) = ((X(i,:) - MU(j,:))'*INV(C)*(X(i,:) - MU(j,:))).^(1/2)
% Copyright (c) 1999 Michael Kiefte.
% $Log$
error(nargchk(2, 3, nargin))
if isempty(X) | ~isa(X, 'double') | ~isreal(X) | ...
any(any(isnan(X) | isinf(X)))
error(['X must be a vector or matrix of real, finite numeric' ...
' doubles.'])
elseif length(X) == prod(size(X))
X = X(:)';
elseif ndims(X) ~= 2
error('If X is a matrix, it must be a 2-d array.')
end
[n p] = size(X);
if isempty(Mu) | ~isa(Mu, 'double') | ~isreal(Mu) | ...
any(any(isnan(Mu) | isinf(Mu)))
error(['Mu must be a vector or matrix of real, finite numeric' ...
' doubles.'])
elseif length(Mu) == prod(size(Mu))
Mu = Mu(:)';
elseif ndims(Mu) ~= 2
error('If MU is a matrix, it must be a 2-d array.')
end
if length(Mu) == 1 & Mu == 0
Mu = zeros(1, p);
elseif size(Mu, 2) ~= p
error('Number of features in MU and X must be the same.')
end
g = size(Mu, 1);
if ~isempty(C)
if ~isa(C, 'double') | ~isreal(C) | ndims(C) ~= 2 | ...
any(any(isnan(C) | isinf(C)))
error('C must be a matrix of real, finite numeric doubles.')
elseif any(size(C) ~= p)
error(['Number of rows and columns in C must match number of' ...
' features in X and MU.'])
end
try
S = inv(chol(C));
catch
error(['Covariance matrix C must be positive, definite,' ...
' symmetric.'])
end
Xs = X*S;
Ms = Mu*S;
else
Xs = X;
Ms = Mu;
end
d = sqrt(repmat(sum(Xs.^2, 2), 1, g) - 2*Xs*Ms' + ...
repmat(sum(Ms'.^2), n, 1));