-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathpca2.m
More file actions
32 lines (32 loc) · 740 Bytes
/
pca2.m
File metadata and controls
32 lines (32 loc) · 740 Bytes
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
%% PCA version2
% Input: X, y, k
% Output: W, mu
function [W , mu ] = pca2 (X , y , k)
[n , d] = size (X );
mu = mean (X);
Xm = X - repmat (mu , size(X,1) , 1) ;
if(n >d )
C = Xm'* Xm ;
[W , D] = eig (C) ;
% sort eigenvalues and eigenvectors
[D , i] = sort ( diag (D) , 'descend');
W = W (: , i );
% keep k components
W = W (: ,1: k);
else
C = Xm *Xm';
%C = cov(Xm ’);
[W , D] = eig (C) ;
% multiply with data matrix
W = Xm'* W ;
% normalize eigenvectors
for i =1: n
W (: , i) = W (: , i )/ norm (W (: , i)) ;
end
% sort eigenvalues and eigenvectors
[D , i] = sort ( diag (D) , 'descend');
W = W (: , i );
% keep k components
W = W (: ,1: k);
end
end