开发者

How do I fix this ArrayIndexOutOfBounds error in Jama?

I am using jama libarary for matrix. I used following matrix but when i tried to get S, it gave me error.

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

When I tried to get S it produce following error.

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

Here is the code

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.p开发者_JAVA技巧rintln("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();       
    }

}


For Jama's singular value decomposition, the number of rows must not be less than the number of columns. Maybe you should try SVD on the transpose of the matrix you provided.

EDIT: Here's the relevant code from 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 is constructed to be an n x n array, so the only possible source of an ArrayIndexOutOfBoundsException is from the reference to this.s[i].

Space for s is initialized in the SingularValueDecomposition constructor (amd no where else) like this:

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

So the Jama implementation will work for a 2x3 input (contradicting what they say in the class javadoc). But I bet it won't work for a 2x4 input.


Could you show us the code that is accessing the matrix? The exception you get clearly indicates that you are trying to index outside of the legal bounds of the underlying array.


It's a 3x11 array. The fact that you're getting an index out of bounds exception for i = 4 suggests to me that your row count is specified incorrectly somewhere.

Another library like Apache Commons Math might help, but I don't believe the library is the issue here. It's your lack of understanding of SVD that's the real problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜