forked from PRML/PRMLT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdimPca.m
37 lines (32 loc) · 887 Bytes
/
dimPca.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
function [V, A] = dimPca(X, p)
% Perform standard PCA (spectral method).
% X: d x n data matrix
% p: dimension of target space (p>=1) or ratio (0<p<1)
% Written by Michael Chen ([email protected]).
opts.disp = 0;
opts.issym = 1;
opts.isreal = 1;
opts.maxit = 500;
[d,n] = size(X);
if nargin == 1
p = min(d,n);
end
X = bsxfun(@minus,X,mean(X,2));
if 0<p && p<1 % given ratio
[V,A] = svd(X,'econ');
A = diag(A).^2;
S = cumsum(A);
idc = (S/S(end))<=p;
V = V(:,idc);
A = A(idc);
elseif p >= min(d,n) % full pca
[V,A] = svd(X,'econ');
A = diag(A).^2;
elseif d <= n % covariance based pca
[V,A] = eigs(X*X',p,'la',opts);
A = diag(A);
elseif d > n % inner product based pca
[U,A] = eigs(X'*X,p,'la',opts);
A = diag(A);
V = X*bsxfun(@times,U,1./sqrt(A)');
end