javamatrixjama

Jama package, 4x4 linear equation solver


I'm trying to solve a 4x4 linear equation system (4 variables, 4 equations) using Jama. I have tried the following code, but it doesn't work. I would appreciate if someone can help me, using Jama or any other method.

import Jama.Matrix;

public class OvaWork {

    public OvaWork() 
    {

        //Creating  Arrays Representing Equations
        double[][] lhsArray = {{-3, 1, -1}, {5, -2, 1}, {-1, 1, 3}, {2, 5, 7}};
        double[] rhsArray = {-4, 6, 0, 8};
        //Creating Matrix Objects with arrays
        Matrix lhs = new Matrix(lhsArray);
        Matrix rhs = new Matrix(rhsArray, 4);
        //Calculate Solved Matrix
        Matrix ans = lhs.solve(rhs);
        //Printing Answers
        System.out.println("w = " + Math.round(ans.get(0, 0)));
        System.out.println("x = " + Math.round(ans.get(1, 0)));
        System.out.println("y = " + Math.round(ans.get(2, 0)));
        System.out.println("z = " + Math.round(ans.get(3, 0)));
    }

    public static void main(String[] args) 
    {
        OvaWork o = new OvaWork();
    }
}

Solution

  • You have to try with easier examples like this 2x2 equation

    double[][] lhsArray = {{1,1},{2, 0}};
    double[] rhsArray = {10,2};
    Matrix lhs = new Matrix(lhsArray);
    Matrix rhs = new Matrix(rhsArray, 2);
    Matrix ans = lhs.solve(rhs);
    

    It works and the output is a matrix {1,9}

    The problem with your code is that your matrix is not square it is 3x4

    double[][] lhsArray = {{-3, 1, -1}, {5, -2, 1}, {-1, 1, 3}, {2, 5, 7}};
    

    Change your matrix to a square one.

    Test this trivial equation:

    double[][] lhsArray = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}};
    double[] rhsArray = {1, 2, 3, 4};
    Matrix lhs = new Matrix(lhsArray);
    Matrix rhs = new Matrix(rhsArray, 4);
    Matrix ans = lhs.solve(rhs);
    

    The ans is {1,2,3,4} as expected.