%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% LDA	Perform a linear discriminant analysis
%
%	Inputs: TrainData,       			- Train,test data arranged in columns
%           Train Targets          		- vectors of class membership
%	Outputs:            				- probability of error
%                                       - predicted values
%			Wg,Cg 						- LDA weights and offsets
% (c) Kevin Englehart,1997
%   Modified by Levi Hargrove, 2005
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [Wg,Cg] = lda(TrainData,TrainClass)

N = size(TrainData,1);
K = max(TrainClass);

%%-- Compute the means and the pooled covariance matrix --%%
C = zeros(N,N);
totMean = mean(TrainData')';
temp = zeros(length(totMean),length(totMean));
for l = 1:K;
	idx = find(TrainClass==l);
	Mi(:,l) = mean(TrainData(:,idx)')';
    temp = temp+(Mi(:,l)-totMean)*(Mi(:,l)-totMean)';
	 C = C + cov((TrainData(:,idx)-Mi(:,l)*ones(1,length(idx)))');
end

C = C./K;
Pphi = 1/K;
Cinv = inv(C);

for i = 1:K
	Wg(:,i) = Cinv*Mi(:,i);
	Cg(:,i) = -1/2*Mi(:,i)'*Cinv*Mi(:,i) + log(Pphi)';
end

return;
