2014-03-14 52 views
0

我正在使用下面的函數庫求解線性方程。該庫的鏈接如下: efficient-java-matrix-library通過高效的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) 

我不明白爲什麼我得到這個錯誤。你能幫我解決這個錯誤嗎?

+0

檢查您的B2數組值。有些可能超出允許的範圍(0,1) – dragon66

+0

B2數組的值將始終在0到1之間。爲什麼? –

回答

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"); 
    }