Java inverse matrix calculation

后端 未结 11 1235
难免孤独
难免孤独 2020-12-03 07:58

I\'m trying to calculate the inverse matrix in Java.

I\'m following the adjoint method (first calculation of the adjoint matrix, then transpose this matrix and fina

11条回答
  •  天涯浪人
    2020-12-03 08:52

    Since ACM library has updated over the years, here is the implementation conforming to latest definition for matrix inversion.

    import org.apache.commons.math3.linear.Array2DRowRealMatrix;
    import org.apache.commons.math3.linear.ArrayRealVector;
    import org.apache.commons.math3.linear.DecompositionSolver;
    import org.apache.commons.math3.linear.LUDecomposition;
    import org.apache.commons.math3.linear.RealMatrix;
    import org.apache.commons.math3.linear.RealVector;
    
    public class LinearAlgebraDemo
    {
        public static void main(String[] args)
        {
            double [][] values = {{1, 1, 2}, {2, 4, -3}, {3, 6, -5}};
            double [][] rhs = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
    
            // Solving AB = I for given A
            RealMatrix A = new Array2DRowRealMatrix(values);
            System.out.println("Input A: " + A);
            DecompositionSolver solver = new LUDecomposition(A).getSolver();
    
            RealMatrix I = new Array2DRowRealMatrix(rhs);
            RealMatrix B = solver.solve(I);
            System.out.println("Inverse B: " + B);
        }
    }
    

提交回复
热议问题