| 1 |
function [vU2,dU2] = eigsort(U,desI) |
| 2 |
% E = EIGSORT(X,desI) is a vector containing the eigenvalues of a square |
| 3 |
% matrix X, where E is sorted descendingly if desI=1 or ascendingly otherwise |
| 4 |
% |
| 5 |
% [V,D] = EIG(X) produces a diagonal matrix D of eigenvalues and a |
| 6 |
% full matrix V whose columns are the corresponding eigenvectors so |
| 7 |
% that X*V = V*D. |
| 8 |
% |
| 9 |
% Written 9/6/98 by Tao Zha |
| 10 |
% |
| 11 |
% Copyright (C) 1997-2012 Tao Zha |
| 12 |
% |
| 13 |
% This free software: you can redistribute it and/or modify |
| 14 |
% it under the terms of the GNU General Public License as published by |
| 15 |
% the Free Software Foundation, either version 3 of the License, or |
| 16 |
% (at your option) any later version. |
| 17 |
% |
| 18 |
% It is distributed in the hope that it will be useful, |
| 19 |
% but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 20 |
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 21 |
% GNU General Public License for more details. |
| 22 |
% |
| 23 |
% If you did not received a copy of the GNU General Public License |
| 24 |
% with this software, see <http://www.gnu.org/licenses/>. |
| 25 |
% |
| 26 |
|
| 27 |
[vU,dU]=eig(U); |
| 28 |
dUvec = diag(dU); % If dU is SPD, use "abs" in front of diag. This is because, |
| 29 |
% even though dU is supposed to be positive, the numerical solution |
| 30 |
% for a near-zero eigenvalue can be negative. |
| 31 |
% ******************* |
| 32 |
% Second thought: "abs" is not necessary, I think. If negative, it |
| 33 |
% implies zero already -- thus the smallest number |
| 34 |
[dUvec2,dUI2] = sort(dUvec); % ascending |
| 35 |
if desI==1 % if descending is required |
| 36 |
dUvec2 = flipud(dUvec2); |
| 37 |
dUI2 = flipud(dUI2); |
| 38 |
end |
| 39 |
|
| 40 |
if nargout==1 |
| 41 |
vU2 = dUvec2; |
| 42 |
dU2 = NaN; |
| 43 |
else |
| 44 |
vU2 = vU(:,dUI2); |
| 45 |
dU2 = diag(dUvec2); % put it back to matrix form |
| 46 |
end |