Java program to multiply two matrices by passing matrix to a function
Here's a Java program that multiplies two matrices by passing the matrices to a function:
public class MatrixMultiplication { public static void main(String[] args) { int[][] matrix1 = {{1, 2}, {3, 4}}; int[][] matrix2 = {{5, 6}, {7, 8}}; int[][] product = multiplyMatrices(matrix1, matrix2); // print the resulting matrix for (int[] row : product) { for (int value : row) { System.out.print(value + " "); } System.out.println(); } } public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) { int rows1 = matrix1.length; int cols1 = matrix1[0].length; int rows2 = matrix2.length; int cols2 = matrix2[0].length; if (cols1 != rows2) { throw new IllegalArgumentException("Cannot multiply matrices: number of columns in matrix1 must equal number of rows in matrix2"); } int[][] product = new int[rows1][cols2]; for (int i = 0; i < rows1; i++) { for (int j = 0; j < cols2; j++) { int sum = 0; for (int k = 0; k < cols1; k++) { sum += matrix1[i][k] * matrix2[k][j]; } product[i][j] = sum; } } return product; } }
In this program, we define two 2D integer arrays matrix1
and matrix2
that represent the matrices we want to multiply. We then call the multiplyMatrices()
function and pass in these two matrices as arguments.
The multiplyMatrices()
function first checks if the number of columns in matrix1
is equal to the number of rows in matrix2
. If this condition is not met, it throws an IllegalArgumentException
. Otherwise, it initializes a new 2D integer array product
with the correct dimensions to hold the product of the two matrices.
The function then uses three nested for loops to calculate the product of the two matrices. The outer two loops iterate over the rows and columns of the resulting matrix, while the inner loop calculates the dot product of the corresponding row of matrix1
and column of matrix2
. The dot product is accumulated in the sum
variable, and the resulting value is stored in the appropriate position of the product
matrix.
Finally, the function returns the resulting matrix, which we print out in the main program using two nested for loops to iterate over the rows and columns of the matrix.