Finding the Hadamard product of two matrices.
Here’s a Java program that calculates the Hadamard product of two matrices:
public class HadamardProduct { public static int[][] calculateHadamardProduct(int[][] matrix1, int[][] matrix2) { int rows = matrix1.length; int cols = matrix1[0].length; if (rows != matrix2.length || cols != matrix2[0].length) { throw new IllegalArgumentException("Matrices must have the same dimensions."); } 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 main(String[] args) { int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}}; int[][] matrix2 = {{7, 8, 9}, {10, 11, 12}}; int[][] hadamardProduct = calculateHadamardProduct(matrix1, matrix2); System.out.println("Hadamard Product:"); for (int[] row : hadamardProduct) { for (int element : row) { System.out.print(element + " "); } System.out.println(); } } }
This program defines a `calculateHadamardProduct` method that takes two matrices as input and returns their Hadamard product. It first checks if the matrices have the same dimensions, and if not, it throws an `IllegalArgumentException`. Then, it initializes a result matrix with the same dimensions as the input matrices. It calculates the Hadamard product by multiplying corresponding elements from the two matrices and stores the result in the result matrix. Finally, the `main` method demonstrates the usage of the `calculateHadamardProduct` method with example matrices and prints the resulting Hadamard product to the console.
No comments yet! You be the first to comment.