# Problems with 2 dimensional matrix multiplication in java

I have been having problems with one of my java functions that is supposed to multiply 2 double arrays as matrices.

public static double[][] matrixMultiply(double[][] m, double[][] n) { double[][] multipliedMatrix = new double [m.length][n[0].length]; for (int i=0; i<m.length-1; i++) { for (int j=0; j<n[0].length-1; j++) { for (int k=0; k<n.length-1; k++) { multipliedMatrix[i][j] = multipliedMatrix[i][j] + (m[i][k] * n[k][j]); } } } return multipliedMatrix; }

The i variable is supposed to cycle through each element of m (the first matrix) in the for loop. The j variable is supposed to cycle through each row of the second matrix n and the variable k is supposed to cycle through each element in the first row of the first matrix and the first column of the second matrix. This does not seem to be working correctly and when given the input

[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 1.0, 2.0, 3.0]], [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [1.0, 2.0, 3.0]]

it gives out

[[30.0, 36.0, 0.0], [78.0, 96.0, 0.0], [0.0, 0.0, 0.0]]

rather than

[[34.0, 44.0, 54.0], [86.0, 112.0, 138.0], [30.0, 45.0, 60.0]].

I cannot understand why this is?

## Answers

Fix:

public static double[][] matrixMultiply(double[][] m, double[][] n) { double[][] multipliedMatrix = new double [m.length][n[0].length]; for (int i=0; i<m.length; i++) { for (int j=0; j<n[0].length; j++) { for (int k=0; k<n.length; k++) { multipliedMatrix[i][j] = multipliedMatrix[i][j] + (m[i][k] * n[k][j]); } } } return multipliedMatrix; }

**OUTPUT**

34.044.054.0 86.0112.0138.0 30.045.060.0

**Explanation**
In each loop you should run while the index is smaller than length - not smaller than length-1