wolffd@0
|
1 function [evals, evec] = eigdec(x, N)
|
wolffd@0
|
2 %EIGDEC Sorted eigendecomposition
|
wolffd@0
|
3 %
|
wolffd@0
|
4 % Description
|
wolffd@0
|
5 % EVALS = EIGDEC(X, N computes the largest N eigenvalues of the
|
wolffd@0
|
6 % matrix X in descending order. [EVALS, EVEC] = EIGDEC(X, N) also
|
wolffd@0
|
7 % computes the corresponding eigenvectors.
|
wolffd@0
|
8 %
|
wolffd@0
|
9 % See also
|
wolffd@0
|
10 % PCA, PPCA
|
wolffd@0
|
11 %
|
wolffd@0
|
12
|
wolffd@0
|
13 % Copyright (c) Ian T Nabney (1996-2001)
|
wolffd@0
|
14
|
wolffd@0
|
15 if nargout == 1
|
wolffd@0
|
16 evals_only = logical(1);
|
wolffd@0
|
17 else
|
wolffd@0
|
18 evals_only = logical(0);
|
wolffd@0
|
19 end
|
wolffd@0
|
20
|
wolffd@0
|
21 if N ~= round(N) | N < 1 | N > size(x, 2)
|
wolffd@0
|
22 error('Number of PCs must be integer, >0, < dim');
|
wolffd@0
|
23 end
|
wolffd@0
|
24
|
wolffd@0
|
25 % Find the eigenvalues of the data covariance matrix
|
wolffd@0
|
26 if evals_only
|
wolffd@0
|
27 % Use eig function as always more efficient than eigs here
|
wolffd@0
|
28 temp_evals = eig(x);
|
wolffd@0
|
29 else
|
wolffd@0
|
30 % Use eig function unless fraction of eigenvalues required is tiny
|
wolffd@0
|
31 if (N/size(x, 2)) > 0.04
|
wolffd@0
|
32 fprintf('netlab pca: using eig\n');
|
wolffd@0
|
33 [temp_evec, temp_evals] = eig(x);
|
wolffd@0
|
34 else
|
wolffd@0
|
35 options.disp = 0;
|
wolffd@0
|
36 fprintf('netlab pca: using eigs\n');
|
wolffd@0
|
37 [temp_evec, temp_evals] = eigs(x, N, 'LM', options);
|
wolffd@0
|
38 end
|
wolffd@0
|
39 temp_evals = diag(temp_evals);
|
wolffd@0
|
40 end
|
wolffd@0
|
41
|
wolffd@0
|
42 % Eigenvalues nearly always returned in descending order, but just
|
wolffd@0
|
43 % to make sure.....
|
wolffd@0
|
44 [evals perm] = sort(-temp_evals);
|
wolffd@0
|
45 evals = -evals(1:N);
|
wolffd@0
|
46 %evec=temp_evec(:,1:N);
|
wolffd@0
|
47 if ~evals_only
|
wolffd@0
|
48 if evals == temp_evals(1:N)
|
wolffd@0
|
49 % Originals were in order
|
wolffd@0
|
50 evec = temp_evec(:, 1:N);
|
wolffd@0
|
51 return
|
wolffd@0
|
52 else
|
wolffd@0
|
53 fprintf('netlab pca: sorting evec\n');
|
wolffd@0
|
54 % Need to reorder the eigenvectors
|
wolffd@0
|
55 for i=1:N
|
wolffd@0
|
56 evec(:,i) = temp_evec(:,perm(i));
|
wolffd@0
|
57 end
|
wolffd@0
|
58 end
|
wolffd@0
|
59 end
|