lessthanoptimal / ejml

A fast and easy to use linear algebra library written in Java for dense, sparse, real, and complex matrices.
https://ejml.org
565 stars 117 forks source link

Eigenvectors of replicated eigenvalues #200

Open gcasale opened 2 months ago

gcasale commented 2 months ago

Hi - thanks for a great library. I am having problems in computing the eigenvectors of this matrix

  A=[0.2000    0.3000    0.5000
          0    1.0000         0
          0         0    1.0000]

The matrix describes a (reducible) Markov chain with two identical eigenvalues 1.0. MATLAB gives

>> [V,D]=eigs(A)
V =
    0.3511    0.5300    1.0000
    0.9363         0         0
         0    0.8480         0
D =
    1.0000         0         0
         0    1.0000         0
         0         0    0.2000

This Java code instead miscalculates the second eigenvector associated to the eigenvalue 1.0

        double[][] matrixData = {
                {0.2, 0.3, 0.5},
                {0, 1.0, 0},
                {0, 0, 1.0}
        };
        DMatrixRMaj A = new DMatrixRMaj(matrixData);
        EigenDecomposition_F64<DMatrixRMaj> eig = DecompositionFactory_DDRM.eig(3, true);
        eig.decompose(A);
        DMatrixRMaj D = new DMatrixRMaj(3, 3); 
        DMatrixRMaj V = new DMatrixRMaj(3, 3); 

        for (int i = 0; i < 3; i++) {
            D.set(i, i, eig.getEigenvalue(i).getReal());
            DMatrixRMaj eigVec = eig.getEigenVector(i);
            CommonOps_DDRM.insert(eigVec, V, 0, i);
        }
        System.out.println("Matrix D (eigenvalues):"); D.print();
        System.out.println("Matrix V (eigenvectors):"); V.print();

that prints

Matrix D (eigenvalues):
Type = DDRM , rows = 3 , cols = 3
 1           0           0         
 0           1           0         
 0           0           .2        
Matrix V (eigenvectors):
Type = DDRM , rows = 3 , cols = 3
 .351123442  .351123442  1         
 0           .936329178  0         
 .936329178  0           0