Finding the matrix Hadamard product using element-wise multiplication
Here’s an example of a Java program that finds the Hadamard product of two matrices using element-wise multiplication:
public class HadamardProduct { public static void main(String[] args) { int[][] matrix1 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int[][] matrix2 = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }; int[][] result = findHadamardProduct(matrix1, matrix2); System.out.println("Matrix 1:"); printMatrix(matrix1); System.out.println("Matrix 2:"); printMatrix(matrix2); System.out.println("Hadamard Product:"); printMatrix(result); } public static int[][] findHadamardProduct(int[][] matrix1, int[][] matrix2) { int rows = matrix1.length; int cols = matrix1[0].length; int[][] result = new int[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { result[i][j] = matrix1[i][j] * matrix2[i][j]; } } return result; } public static void printMatrix(int[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } System.out.println(); } }
In this program, we have two input matrices, `matrix1` and `matrix2`, defined as two-dimensional arrays. The `findHadamardProduct` method calculates the Hadamard product by multiplying corresponding elements of the two matrices and stores the result in the `result` array. The `printMatrix` method is used to display the matrices on the console.
When you run this program, it will output the original matrices `matrix1` and `matrix2`, as well as the resulting Hadamard product.
No comments yet! You be the first to comment.