如何在Jama中修复此ArrayIndexOutOfBounds错误?

时间:2010-01-21 21:18:24

标签: java math indexoutofboundsexception jama

我正在使用jama libarary作为矩阵。我使用了以下矩阵但是当我试图得到S时,它给了我错误。

1.0    1.0    0.0    1.0    0.0    0.0    0.0    0.0    0.0   11.0    1.0
1.0    0.0    0.0    0.0    0.0    0.0    1.0    0.0    0.0   12.0    2.0
1.0    1.0    0.0    0.0    0.0    0.0    0.0    0.0    1.0   13.0    3.0

当我试图获得S时,会产生以下错误。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at Jama.SingularValueDecomposition.getS(SingularValueDecomposition.java:507)
    at SVD2.main(SVD2.java:19)

这是代码

public class SVD2 {
    public static void main(String[] args) {
        double[][] vals = {
              {1,1,0,1,0,0,0,0,0,11,1},
              {1,0,0,0,0,0,1,0,0,12,2},
              {1,1,0,0,0,0,0,0,1,13,3}
              };
        Matrix A = new Matrix(vals,3,11);
        System.out.println("The Matrix A is ");
        A.print(11, 2);
        System.out.println();

        System.out.println("The SVD of A is ");
        SingularValueDecomposition svd = A.svd();
        Matrix S = svd.getS();       
    }

}

3 个答案:

答案 0 :(得分:3)

对于 Jama的奇异值分解,the number of rows must not be less than the number of columns。也许你应该在你提供的矩阵的转置上尝试SVD。

编辑:以下是SingularValueDecomposition.java的相关代码:

   public Matrix getS () {
      Matrix X = new Matrix(n,n);
      double[][] S = X.getArray();
      for (int i = 0; i < n; i++) {
         for (int j = 0; j < n; j++) {
            S[i][j] = 0.0;
         }
         S[i][i] = this.s[i];
      }
      return X;
   }

S被构造为n x n数组,因此ArrayIndexOutOfBoundsException的唯一可能来源是this.s[i]的引用。

s的空间在SingularValueDecomposition构造函数(amd no where else)中初始化,如下所示:

s = new double [Math.min(m+1,n)];

所以Jama的实现将适用于2x3输入(与他们在javadoc类中所说的相矛盾)。但我敢打赌它不适用于2x4输入。

答案 1 :(得分:0)

你能告诉我们访问矩阵的代码吗?您得到的异常清楚地表明您正在尝试在基础数组的法律边界之外进行索引。

答案 2 :(得分:0)

这是一个3x11阵列。您为i = 4获取索引超出范围异常的事实告诉我您的行数在某处错误地指定。

像Apache Commons Math这样的另一个库可能有所帮助,但我不相信这里的库是问题。这是你对SVD缺乏了解才是真正的问题。

相关问题