01
02
03
04
05
06
07
08
09
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
package algs9; // section 9.9
import stdlib.*;
import Jama.EigenvalueDecomposition;
import Jama.Matrix;

/* ***********************************************************************
 *  Compilation:  javac -classpath .:jama.jar XEigenvalues.java
 *  Execution:    java -classpath .:jama.jar XEigenvalues
 *  Dependencies: jama.jar
 *
 *  Test client for computing eigenvalues and eigenvectors of a real
 *  symmetric matrix A = V D V^T.
 *
 *       http://math.nist.gov/javanumerics/jama/
 *       http://math.nist.gov/javanumerics/jama/Jama-1.0.1.jar
 *
 *************************************************************************/

public class XEigenvalues {
  public static void main(String[] args) {
    int N = 5;

    // create a symmetric positive definite matrix
    Matrix A = Matrix.random(N, N);
    A = A.transpose().times(A);

    // compute the spectral decomposition
    EigenvalueDecomposition e = A.eig();
    Matrix V = e.getV();
    Matrix D = e.getD();

    StdOut.print("A =");
    A.print(9, 6);
    StdOut.print("D =");
    D.print(9, 6);
    StdOut.print("V =");
    V.print(9, 6);

    // check that V is orthogonal
    StdOut.print("||V * V^T - I|| = ");
    StdOut.println(V.times(V.transpose()).minus(Matrix.identity(N, N)).normInf());

    // check that A V = D V
    StdOut.print("||AV - DV|| = ");
    StdOut.println(A.times(V).minus(V.times(D)).normInf());
  }

}