Last Updated: September 12, 2021
·
166
· Bruno Volpato

Multiply matrices in Java

public int[][] matmul(int[][] firstMatrix, int[][] secondMatrix) {
    int[][] result = new int[firstMatrix.length][secondMatrix[0].length];

    for (int row = 0; row < result.length; row++) {
        for (int col = 0; col < result[row].length; col++) {
            result[row][col] = matmulCell(firstMatrix, secondMatrix, row, col);
        }
    }

    return result;
}

public int matmulCell(int[][] firstMatrix, int[][] secondMatrix, int row, int col) {
    int cell = 0;
    for (int i = 0; i < secondMatrix.length; i++) {
        cell += firstMatrix[row][i] * secondMatrix[i][col];
    }
    return cell;
}