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 [temp_evec, temp_evals] = eig(x);
|
wolffd@0
|
33 else
|
wolffd@0
|
34 options.disp = 0;
|
wolffd@0
|
35 [temp_evec, temp_evals] = eigs(x, N, 'LM', options);
|
wolffd@0
|
36 end
|
wolffd@0
|
37 temp_evals = diag(temp_evals);
|
wolffd@0
|
38 end
|
wolffd@0
|
39
|
wolffd@0
|
40 % Eigenvalues nearly always returned in descending order, but just
|
wolffd@0
|
41 % to make sure.....
|
wolffd@0
|
42 [evals perm] = sort(-temp_evals);
|
wolffd@0
|
43 evals = -evals(1:N);
|
wolffd@0
|
44 if ~evals_only
|
wolffd@0
|
45 if evals == temp_evals(1:N)
|
wolffd@0
|
46 % Originals were in order
|
wolffd@0
|
47 evec = temp_evec(:, 1:N);
|
wolffd@0
|
48 return
|
wolffd@0
|
49 else
|
wolffd@0
|
50 % Need to reorder the eigenvectors
|
wolffd@0
|
51 for i=1:N
|
wolffd@0
|
52 evec(:,i) = temp_evec(:,perm(i));
|
wolffd@0
|
53 end
|
wolffd@0
|
54 end
|
wolffd@0
|
55 end |