-
Notifications
You must be signed in to change notification settings - Fork 15
/
CanonCor2.m
54 lines (46 loc) · 1.23 KB
/
CanonCor2.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
% [a b R2 V] = CanonCor2(Y, X)
%
% does a sort of canonical correlation analysis on two sets of data X and Y
% except that now it finds the linear combinations of X that predict
% the largest variance fractions of Y.
%
% You should think of Y as the dependent variable, and X as the independent
% variable.
%
% R2 is the fraction of the total variance of Y explained by
% the nth projection
%
% the approximation of Y based on the first n projections is:
% Y = X * b(:,1:n) *a'(:,1:n);
%
% the nth variable for the ith case gives the approximation
% Y(i,:)' = a(:,n) * b(:,n)' * X(i,:)'
%
%
% V is the actual value of the nth linear combination of X.
function [a, b, R2, V] = CanonCor2(Y, X, lam)
% Make covariance matrices
XSize = size(X, 2);
YSize = size(Y, 2);
BigCov = cov([X, Y]);
CXX = BigCov(1:XSize, 1:XSize) + lam*eye(XSize);
CYY = BigCov(XSize+1:end, XSize+1:end);
%CXY = BigCov(1:XSize, XSize+1:end);
CYX = BigCov(XSize+1:end, 1:XSize);
CXXMH = CXX ^ -0.5;
% matrix to do svd ...
M = CYX * CXXMH;
M(isnan(M)) = 0;
% do svd
[d s c] = svdecon(M);
b = CXXMH * c;
if sum(isnan(d(:,end))) > 0
d = d(:, 1:end-1);
s = s(1:end-1, 1:end-1);
b = b(:, 1:end-1);
end
a = d * s;
R2 = (diag(s).^2)/sum(var(Y));
if (nargout > 3)
V = X*b;
end;