1

I'm trying to multiply 2 arrays in Java. I know how to multiply 2 arrays with each other, but I'm struggling to translate that into Java using 2D arrays (It's my first time using 2D arrays).

I've tried creating a new column variable for the first array, another one for the second one, and another one for the result, but it's not working.

This is what I've written so far

public double[][] producto(double[][] m1, double[][] m2){
        double[][] r=new double[m1.length][m1[0].length];
        for(int fila=0, col1 = 0, col=0;fila<m1.length && col1<m1[fila].length;fila++,col1++,col++){
            for(int col2=0; col2<m1[fila].length;col2++){
                r[fila][col]+=m1[fila][col1]*m2[fila][col2];
            }
        }
        return r;
    }

When I use {{1,1,1},{1,1,1},{1,1,1}} and {{2,2,2},{2,2,2},{2,2,2}} as inputs I get tze actual output {{6,0,0},{0,6,0},{0,0,6}} while I would expect it to be {{6,6,6},{6,6,6},{6,6,6}}.

CDAMXI
  • 35
  • 5
  • 1
    This is solved here: https://stackoverflow.com/questions/21547462/how-to-multiply-2-dimensional-arrays-matrix-multiplication – Dheeraj Mar 11 '23 at 22:14
  • Please repeat for me, how does one multiply two matrices? I would have expected three nested loops, not just two? – Ole V.V. Mar 11 '23 at 23:14

1 Answers1

1

You are missing an inner loop :

  public double[][] producto(double[][] m1, double[][] m2){
    final int nbRow1 = m1.length;
    final int nbColumn1 = m1[0].length;
    final int nbRow2 = m2.length;
    final int nbColumn2 = m2[0].length;

    if (nbColumn1 != nbRow2) {
      throw new IllegalArgumentException("Invalid input");
    }

    double[][] r=new double[nbRow1][nbColumn2];
    for(int row=0;row<nbRow1;row++){
      for(int col=0; col<nbColumn2;col++){
        r[row][col] = 0;
        for (int i = 0; i < nbColumn1; i++) {
          r[row][col]+=m1[row][i]*m2[i][col];
        }
      }
    }
    return r;
  }
Bastien Aracil
  • 1,531
  • 11
  • 6