Free Response Question 2: Multiply the Matrices

In this exercise, you'll multiply the two matrices.

Background

In high school, you likely have studied matrix multiplication and its properties. Here’s an article in case you don’t remember it.

In this challenge, you’re required to perform matrix multiplication with Java.

Problem statement

Intent: Design a multiply() function that takes two input matrices ( 2D arrays) and a resultant matrix (a 2D array) as parameters and returns true or false depending on the input matrices.

  • Declare the header of the multiply method correctly.
  • If the number of columns of the first matrix is not equal to the number of rows of the second matrix, return false because multiplication isn’t possible.
  • If the number of columns of the first matrix is equal to the number of rows of the second matrix, calculate the resultant matrix and return true. Update the resultant matrix right away in the method. As it’s a reference object, the changes will automatically be seen outside the local scope.

How do we multiply matrices?

Look at the equation below. The value of the resultant matrix, at the first row, first column, is calculated as:

product11 = (matrix111 * matrix211) + (matrix112 * matrix221) + ... +(matrix11m * matrix2m1)

Here:

  • matrix111 is the value of matrix1 at the 1st row and 1st column.
  • matrix211 is the value of matrix2 at the 1st row and 1st column.
  • matrix112 is the value of matrix1 at the 1st row and 2nd column.
  • matrix221 is the value of matrix2 at the 2nd row and 1st column.
  • matrix11m is the value of matrix1 at the 1st row and mth column
  • matrix2m1 is the value of matrix2 at the mth row and 1st column

Get hands-on with 1400+ tech skills courses.