Search code examples
javaarraysmatrixmultidimensional-arraymatrix-multiplication

Multiplying matrices Java


I've been have some problems multiplying the matrices for this code, when I do it by hand and with a calculation tool I get something completely different than what my code is giving me.

Code:

public class mult1 {
  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    double[][] colaO = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//orginal
    double[][] colaD = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//copy
    double[][] colaC = {{.9,0.05,0.05},{0.05,.9,0.05},{0.05,0.05,.9}};//for algs
    mult1 test = new mult1();
    test.output(colaC);
    test.Alg1(colaO, colaD, colaC);
    test.output(colaC);
  }
  public void Alg1(double colaO[][], double colaD[][], double colaC[][]) {
    for (int i = 0; i < colaO.length; i++) {
      for (int j = 0; j < colaO.length; j++) {
        for (int k = 0; k < colaO.length; k++) {
          colaC[i][j] += colaO[i][k] * colaD[k][j];
        }
      }
    }
  }
  public void output(double colaC[][]) {
    for (int i = 0; i < colaC.length; i++) {
      for (int j = 0; j < colaC.length; j++) {
        System.out.printf("%.3f", colaC[i][j]);
        System.out.print(" ");
      }
      System.out.println();
    }
  }
}

Results:

 ---original-----
 0.900 0.050 0.050 
 0.050 0.900 0.050 
 0.050 0.050 0.900 
 ---what i'm getting------
 1.715 0.143 0.143 
 0.143 1.715 0.143 
 0.143 0.143 1.715 
 ---should be-----
 0.815 0.092 0.092
 0.092 0.815 0.092
 0.092 0.092 0.815

I don't quite see where I'm messing up the equation


Solution

  • Well the first thing I would do is 0-initialise colaC since you're using += on its entries. The way you're doing it now can't lead to the correct result.