-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathPCA.m
More file actions
56 lines (51 loc) · 1.71 KB
/
PCA.m
File metadata and controls
56 lines (51 loc) · 1.71 KB
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 [Y,Z,eigVal,eigVec] = PCA(X,dim,centering)
%
% Principal component analysis
% This function supports both PCAs with and without data centering.
%
% Coded by D. Kitamura (d-kitamura@ieee.org)
%
% See also:
% http://d-kitamura.net
%
% [syntax]
% [Y,Z,eigVal,eigVec] = PCA(X)
% [Y,Z,eigVal,eigVec] = PCA(X,dim)
% [Y,Z,eigVal,eigVec] = PCA(X,dim,centering)
%
% [inputs]
% X: input data ( K (variables) x N (samples) )
% dim: number of dimensions to which X is projected
% centering: centering X before applying PCA or not (true or false, default: true)
%
% [outputs]
% Y: output matrix (dim x N)
% Z: transformation matrix (dim x K, Y = ZX)
% eigVal: all eigenvalues (K x 1)
% eigVec: all eigenvectors (K x K)
% Check errors and set default values
if (nargin < 3)
centering = true; % Default setting
end
[K,N] = size(X); % variables x samples
if centering
cX = X - mean(X,2); % Data centering (using implicit expansion)
% cX = X - repmat(mean(X,2),1,N); % Data centering (prior to R2016b)
else
cX = X; % Do not apply centering
end
V = cX*(cX')/N; % Covariance matrix of data matrix
[P,D] = eig(V); % Eigenvalue decomposition (V = P*D*inv(P), P includes eigenvectors and D is a diagonal matrix with eigenvalues)
% Sort eigenvalues in descending order
eigVal = diag(D);
[eigVal,idx] = sort(eigVal,'descend');
D = D(idx,idx);
P = P(:,idx);
% Pick up top-dim eigenvalues and their eigenvectors
reducedD = D(1:dim,1:dim);
reducedP = P(:,1:dim);
Y = reducedP'*cX; % Output matrix
Z = reducedP'; % Transformation matrix
eigVec = P; % All eigenvectors
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EOF %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%