Solution Review: Multiply the Matrices
Have a look at the solution to the 'Multiply the Matrices' challenges.
We'll cover the following...
Rubric criteria
Solution
Press + to interact
class Multiply{public static void main(String args[]){// Creating matricesint[][] matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};int[][] matrix2 = {{1, 2}, {4, 2}, {7, 2}};int[][] product = new int[matrix1.length][matrix2[0].length];if (multiply(matrix1, matrix2, product)) // If multiplication possible // Calling the method{// Printing the product arrayfor(int i = 0; i < product.length; i++){for(int j = 0; j < product[i].length; j++){System.out.print(product[i][j]);System.out.print(" ");}System.out.print("\n");}}else{System.out.println("Multiplication order not satisfied.");}}// Method to multiply matricespublic static boolean multiply(int[][] matrix1, int[][] matrix2, int[][]product){if (matrix1[0].length == matrix2.length){for(int i = 0; i < matrix1.length; i++){for(int j = 0; j < matrix2[i].length; j++){for(int k = 0; k < matrix1[i].length; k++){product[i][j] += matrix1[i][k] * matrix2[k][j];}}}return true;}else{return false;}}}
Rubric-wise explanation
Initially, we create two 2D arrays: matrix1
and matrix2
. Then, we create a 2D array, product
, to store the ...