下面是一个使用MATLAB编写LDA(Linear Discriminant Analysis)建模与分类函数的示例程序:
% Load the fisheriris data set
load fisheriris;
% Select two classes (1~50, 51~100) for classification
X = [meas(1:50,:); meas(51:100,:)];
y = [ones(50,1); 2*ones(50,1)];
% Compute the means of the two classes
mu1 = mean(X(y==1,:));
mu2 = mean(X(y==2,:));
% Compute the within-class scatter matrix
S1 = zeros(size(X,2));
for i = 1:50
if y(i) == 1
S1 = S1 + (X(i,:) - mu1)'*(X(i,:) - mu1);
end
end
S2 = zeros(size(X,2));
for i = 51:100
if y(i) == 2
S2 = S2 + (X(i,:) - mu2)'*(X(i,:) - mu2);
end
end
Sw = S1 + S2;
% Compute the LDA projection vector
w = inv(Sw)*(mu2 - mu1)';
% Project the data onto the LDA vector
X_lda = X * w;
% Perform classification on the projected data
y_pred = zeros(size(X,1),1);
for i = 1:size(X,1)
if X_lda(i) > 0
y_pred(i) = 1;
else
y_pred(i) = 2;
end
end
% Compute the classification accuracy
ac