通过高效的java-matrix-library求解线性方程

时间:2014-03-14 03:21:31

标签: java matrix linear-algebra

我使用以下库来求解线性方程。该库的链接如下: efficient-java-matrix-library

我已经下载了库文件并在eclipse中导入。然后我写了下面的代码来解决一组线性方程。

 SimpleMatrix A1 = new SimpleMatrix(m,n);
      SimpleMatrix b1 = new SimpleMatrix(m,1);

      for(int i=0;i<m;i++)
      {
          for(int j=0;j<n;j++)
          {
              A1.setRow(i, i, A2[i][j]);
             // System.out.println();
          }
           b1.setColumn(i, 0, B2[i]); 
      }
      try {
          SimpleMatrix x1 = A1.solve(b1);
          for(int i=0;i<x1.getNumElements();i++)
          {
              double value = x1.get(i, 0);
              System.out.println(" value of x"+i+" is "+value);
          }
      } 
      catch ( SingularMatrixException e ) 
      {
        //  throw new IllegalArgument("Singular matrix");
      }

但是对于这段代码,我遇到以下异常。

Exception in thread "main" java.lang.IllegalArgumentException: Specified element is out of bounds: (0 , 1)
    at org.ejml.data.DenseMatrix64F.set(Unknown Source)
    at org.ejml.simple.SimpleBase.setColumn(Unknown Source)
    at com.temp.temp.Main_function.main(Main_function.java:37)

我无法理解为什么会收到此错误。你能帮我解决这个错误吗?

1 个答案:

答案 0 :(得分:0)

SimpleMatrix A1 = new SimpleMatrix(m,n);       SimpleMatrix b1 = new SimpleMatrix(m,1);

  for(int i=0;i<m;i++)
  {
      for(int j=0;j<n;j++)
      {
          A1.setRow(i, j, A2[i][j]);
          double value1 = A1.get(i,j);
          System.out.print(" "+value1);
          // System.out.println();
      }
      b1.setRow(i,0, B2[i]); 
      double value2 = b1.get(i,0);
      System.out.print(" = "+value2);
      System.out.println();
  }


  try {
      SimpleMatrix x1 = A1.solve(b1);
      for(int i=0;i<x1.getNumElements();i++)
      {
          double value = x1.get(i, 0);
          System.out.println(" value of x"+i+" is "+value);
      } 
  } 
  catch ( SingularMatrixException e ) 
  {
    //  throw new IllegalArgument("Singular matrix");
  }