-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcalc_pca.m
71 lines (61 loc) · 1.24 KB
/
calc_pca.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
%==========================================================================
% Do PCA to 2-d vectors
%
% input :
%
% output :
%
% Siqi Li, SMAST
% yyyy-mm-dd
%
% Updates:
%
%==========================================================================
function [u, v, variance, theta] = calc_pca(u0, v0)
% clear, clc, close all
%
% % Generate a test dataset
% rng(0)
% data(:,1) = randn(30,1);
% data(:,2) = 3.4 + 1.2 * data(:,1);
% data(:,2) = data(:,2) + 0.2*randn(size(data(:,1)));
% data = sortrows(data,1);
% data = [data; nan nan];
% u0 = data(:,1);
% v0 = data(:,2);
% %
dims = size(u0);
k = find(~isnan(u0+v0));
u = u0(k);
u = u(:);
v = v0(k);
v = v(:);
% Step 1
% Remove the mean
% umean = mean(u);
% vmean = mean(v);
% u = u - umean;
% v = v - vmean;
data = [u v];
% Step 2
% Calculate the covariance matrix
C = cov(data);
% Step 3
% Calculate the eigenvalues
[V, D] = eig(C);
% Step 4
% Calculating the data set in the new coordinate system.
newdata = V' * data';
newdata = newdata';
variance = D / sum(D(:));
if D(2,2) > D(1,1)
newdata = fliplr(newdata);
theta = atan2d(V(2,2), V(1,2));
variance = variance([4 1]);
else
theta = atan2d(V(2,1), V(1,1));
end
u = nan(dims);
v = nan(dims);
u(k) = newdata(:,1);
v(k) = newdata(:,2);