-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcca.m
48 lines (47 loc) · 1.63 KB
/
cca.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
function [Wx, Wy, r] = cca(X,Y)
% CCA calculate canonical correlations
%
% [Wx Wy r] = cca(X,Y) where Wx and Wy contains the canonical correlation
% vectors as columns and r is a vector with corresponding canonical
% correlations. The correlations are sorted in descending order. X and Y
% are matrices where each column is a sample. Hence, X and Y must have
% the same number of columns.
%
% Example: If X is M*K and Y is N*K there are L=MIN(M,N) solutions. Wx is
% then M*L, Wy is N*L and r is L*1.
%
%
% ?? 2000 Magnus Borga, Link?pings universitet
% --- Calculate covariance matrices ---
[m1,n1]=size(Y);
for m2=1:m1
for n2=1:n1
if isnan(Y(m2,n2))
Y(m2,n2)=randn(1);
end
end
end
z = [X;Y];
C = cov(z.');
sx = size(X,1);
sy = size(Y,1);
Cxx = C(1:sx, 1:sx) + 10^(-8)*eye(sx);
Cxy = C(1:sx, sx+1:sx+sy);
Cyx = Cxy';
Cyy = C(sx+1:sx+sy, sx+1:sx+sy) + 10^(-8)*eye(sy);
invCyy = pinv(Cyy);
% --- Calcualte Wx and r ---
[Wx,r] = eig(pinv(Cxx)*Cxy*invCyy*Cyx); % Basis in X
r = sqrt(real(r)); % Canonical correlations
% --- Sort correlations ---
V = fliplr(Wx); % reverse order of eigenvectors
r = flipud(diag(r)); % extract eigenvalues and reverse their order
[r,I]= sort((real(r))); % sort reversed eigenvalues in ascending order
r = flipud(r); % restore sorted eigenvalues into descending order
for j = 1:length(I)
Wx(:,j) = V(:,I(j)); % sort reversed eigenvectors in ascending order
end
Wx = fliplr(Wx); % restore sorted eigenvectors into descending order
% --- Calcualte Wy ---
Wy = invCyy*Cyx*Wx; % Basis in Y
% Wy = Wy./repmat(sqrt(sum(abs(Wy).^2)),sy,1); % Normalize Wy