-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpca_fun.m
56 lines (48 loc) · 2.23 KB
/
pca_fun.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
function [eigenval,eigenvec,explain,Y,mean_vec]=pca_fun(X,m)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% FUNCTION
% [eigenval,eigenvec,explain,Y,mean_vec]=pca_fun(X,m)
% Performs principal component analysis on a data set X and
% returns: (a) the eigenvalues, eigenvectors of the first m principal
% components, (b) the percentage of the total variance explained by each
% principal component, (c) the projections of the data points to the
% space spanned by the first m principal components and (d) the mean of X.
%
% INPUT ARGUMENTS:
% X: lxN matrix whose columns are the data vectors.
% m: the number of the most significant principal components that
% are taken into account.
%
% OUTPUT ARGUMENTS:
% eigenval: m-dimensional column vector containing the m largest
% eigenvalues of the covariance matrix of X, in descending order.
% eigenvec: lxm matrix whose i-th column corresponds to
% the i-th largest eigenvalue of the covariance matrix of X.
% explain: l-dimensional column vector, whose i-th element is the
% percentage of the total variance explained by the i-th
% principal component.
% Y: mxN matrix whose i-th column is the projection
% of the i-th column vector of X on the space spanned by the
% first m principal components.
% mean_vec: the mean vector of X (l-dimensional column vector).
%
% (c) 2010 S. Theodoridis, A. Pikrakis, K. Koutroumbas, D. Cavouras
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[l,N]=size(X);
% Subtracting the mean
mean_vec=mean(X')';
X_zero=X-mean_vec*ones(1,N);
% Computing the covariance matrix and its eigenvalues/eigenvectors
R=cov(X_zero');
[V,D]=eig(R);
eigenval=diag(D); %diatasume analoga me tin idiotimi, prwta t megisto klp klp
[eigenval,ind]=sort(eigenval,1,'descend');
eigenvec=V(:,ind);
explain=eigenval/sum(eigenval); % λ1/(λ1+λ2) και για τη 2η λ2/(λ1+λ2)
% Keeping the first m eigenvaules/eigenvectors
eigenval=eigenval(1:m); %diatirisis megaluteru variance stis m diastaseis
eigenvec=eigenvec(:,1:m);
% Computing the transformation matrix
A=eigenvec(:,1:m)';
% Computing the transformed data set
Y=A*X;