title: Multiplying two matrices with Java
body: <p>I try to multiplying 2 matrices.
  I tried with R software: check this thread: <a href="https://stackoverflow.com/questions/9894068/multiplying-two-matrices-in-r">Multiplying two matrices in R</a></p>
  
  <p>Now i try to do the same thing in Java.</p>
  
  <p>I use Jama library for matrix.</p>
  
  <p>my power function</p>
  
  <pre><code>public Matrix power(Matrix M, double p) {
      EigenvalueDecomposition evd = M.eig();
      Matrix D = evd.getD();
      for (int i = 0; i &lt; D.getColumnDimension(); i++) {
          D.set(i, i, Math.pow(D.get(i, i), p));
      }
  
      Matrix V = evd.getV();
  
      return V.times(D.times(V.transpose()));
  }
  
  
  double[][] matDouble1 = {{0.25, 0.25, 0.25, 0.25}};
  double[][] matDouble2 = {{0, 0, 1, 0},
                         {0.333, 0, 0.333, 0.333},
                         {1, 0, 0, 0},
                         {0, 1, 0, 0}};
  Matrix mat1 = new Matrix(matDouble1);
  Matrix mat2 = new Matrix(matDouble2);
  mat2 = power(mat2, 10000);
  mat1 = mat1.times(mat2.transpose());
  </code></pre>
  
  <p>When is display mat1 i get:</p>
  
  <pre><code>0.25018740608813655 0.2498123125257854  0.2501874060881363  0.24981231252578548
  </code></pre>
  
  <p>instead of</p>
  
  <pre><code>0.5 0 0.5 0
  </code></pre>
  
  <p>with R i do</p>
  
  <pre><code>mpower = function(M,p) {
       A = as.matrix(M)
  
      if (dim(A)[1] != dim(A)[2]) stop("not a square matrix")
  
      # M^{-1} = the matrix inverse of M
      if (p==-1) return(solve(A))
  
      # M^0 = I
      if (p==0) return(diag(1,dim(A)[1],dim(A)[2]))
  
      # M^1 = M
      if (p==1) return(A)
  
      if (p &lt; -1) stop("only powers &gt;= -1 allowed")
      if (p != as.integer(p)) stop("only integer powers allowed")
  
      R = A
      for (i in 2:p) {
          R = R %*% A
      }
      return(R)
  </code></pre>
  
  <p>}</p>
  
  <pre><code>mat1&lt;-matrix(c(0.25,0.25,0.25,0.25),nrow=1)
  mat2&lt;-matrix(c(0,0,1,0,0.3,0,0.3,0.3,1,0,0,0,0,1,0,0),nrow=4)
  mat1%*%t(mpower(mat2,10000))
  </code></pre>
  
  <p>i get</p>
  
  <pre><code>[1,] 0.4996252    0 0.4996252    0
  </code></pre>