-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathsorted_eig.m
33 lines (29 loc) · 914 Bytes
/
sorted_eig.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
function [V_sorted, S_sorted] = sorted_eig(X, direction)
%SORTED_EIG Compute the sorted eigenvalue decomposition of a square matrix
%
% Inputs:
% X: matrix to decompose
% direction: 'ascend','descend' for ordering of eigenvectors and
% eigenvalues
%
% Outputs:
% V_sorted: matrix of eigenvectors sorted according to the
% eigenvalues
% S_sorted: diagonal matrix of sorted eigenvalues
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SORTED_EIG.M - 5/10/2016
% Archontis Politis, [email protected]
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
if nargin<2, direction = 'descend'; end
if size(X,1) ~= size(X,2)
error('input matrix should be square')
end
[V, S] = eig(X);
[~, perm] = sort(diag(S), 1, direction);
S_sorted = S(perm, perm); V_sorted = V(:, perm);
end