Search⌘ K

Solution Review: Multiply the Matrices

Explore how to multiply two 2D matrices in Java by validating dimensions and implementing nested loops to compute the product. Understand how to create the result array with proper size and handle cases where multiplication is not possible.

Rubric criteria

Solution

Java
class Multiply
{
public static void main(String args[])
{
// Creating matrices
int[][] 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 array
for(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 matrices
public 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 result of the multiplication. Notice its size. As a result of multiplication, the resultant matrix holds rows equal to the number of rows of the first matrix (matrix1.length) and columns equal to the number of columns of the second matrix ( ...