Matrix multiplication
Here’s an example of a Java program that performs matrix multiplication:
public class MatrixMultiplication { public static void main(String[] args) { int[][] matrix1 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int[][] matrix2 = { {10, 11}, {12, 13}, {14, 15} }; int[][] result = multiplyMatrices(matrix1, matrix2); // Print the result for (int i = 0; i < result.length; i++) { for (int j = 0; j < result[0].length; j++) { System.out.print(result[i][j] + " "); } System.out.println(); } } public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) { int rows1 = matrix1.length; int columns1 = matrix1[0].length; int columns2 = matrix2[0].length; int[][] result = new int[rows1][columns2]; for (int i = 0; i < rows1; i++) { for (int j = 0; j < columns2; j++) { for (int k = 0; k < columns1; k++) { result[i][j] += matrix1[i][k] * matrix2[k][j]; } } } return result; } }
In this example, we have two matrices: `matrix1` and `matrix2`. We define the dimensions and elements of these matrices. The `multiplyMatrices` method takes two matrices as input and performs the matrix multiplication operation, storing the result in a new matrix called `result`. Finally, the program prints the resulting matrix.
Note that matrix multiplication requires the number of columns in the first matrix to be equal to the number of rows in the second matrix. The resulting matrix will have the same number of rows as the first matrix and the same number of columns as the second matrix.
No comments yet! You be the first to comment.