How to overwrite/update a Jama Matrix in Android Studio without any error?

风格不统一 提交于 2019-12-24 03:49:04

问题


Jama Matrices are defined in my code (Matrix computation class) as follows:

private Matrix A;
private Matrix B;
private Matrix C;

The matrix A is initialized as follows:

A = new Matrix(2,2);
A.set(0,0,1.5);
A.set(0,1,0.0);
A.set(1,0,0.0);
A.set(1,1,1.5);

Matrix B is a 2*2 matrix, initialized as an identity matrix and is updated every second by the next matrix of the same size from the MainActivity class.

Matrix C is initialized and computed as follows:

 if(C!=null)
 C = A.plus(C.times(B));
 else {
 C = new Matrix(2,2);
 C.set(0,0,1);
 C.set(0,1,0.0);
 C.set(1,0,0.0);
 C.set(1,1,1);

Here, the Matrix computation class is called by the MainActivity class every second and matrix B is updated accordingly. However, the code runs well for only the first iteration and throws an error in later as follows:

java.lang.IllegalArgumentException: Matrix inner dimensions must agree.

After some digging, I found that it is caused due to matrix overwriting (Matrix B and C). The matrices in my code cannot be static or final. Is there any way to use the Jama matrix when the matrices are not static? Are there any alternatives to Jama in the android studio for Matrix operation?


回答1:


Looking at the source code provided with JAMA, the IllegalArgumentException is thrown at that place:

   /** Linear algebraic matrix multiplication, A * B
   @param B    another matrix
   @return     Matrix product, A * B
   @exception  IllegalArgumentException Matrix inner dimensions must agree.
   */

   public Matrix times (Matrix B) {
      if (B.m != n) {
         throw new IllegalArgumentException("Matrix inner dimensions must agree.");
      }
      Matrix X = new Matrix(m,B.n);
      double[][] C = X.getArray();
      double[] Bcolj = new double[n];
      for (int j = 0; j < B.n; j++) {
         for (int k = 0; k < n; k++) {
            Bcolj[k] = B.A[k][j];
         }
         for (int i = 0; i < m; i++) {
            double[] Arowi = A[i];
            double s = 0;
            for (int k = 0; k < n; k++) {
               s += Arowi[k]*Bcolj[k];
            }
            C[i][j] = s;
         }
      }
      return X;
   }

So appearently C.times(B) fails, which means that C and B dimensions do not agree. As we can also see from the line below, C = new Matrix(2,2) does have 2x2 size, which means that B must have a wrong size.

I do not understand what you mean with "matrix overwriting"? C = A.plus(C.times(B)) does allocate a new instance of Matrix internally. This has nothing to do with static or final.

Please provide a complete, minimal example. There are many parts missing, like the place where B is initialized.



来源:https://stackoverflow.com/questions/59024375/how-to-overwrite-update-a-jama-matrix-in-android-studio-without-any-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!