This tutorial first explains how to perform matrix multiplication. It then shows how to implement matrix multiplication in java and explains the java code in detail.
How to perform matrix multiplication
Matrix multiplication formula-
Given two matrices, M and N, with the number of columns of M being equal to number of rows of N, the product of these matrices, denoted by ‘MXN’, contains consists of elements calculated using the formula –
MXN(ricj) = M(rick X N rkcj)
– MXN(ricj) is the number in ricj position of MXN.
– the value of k varies from 1 to ‘no. of columns in M‘.
The multiplication formula in matrix form looks like this –
Having understood how matrix multiplication is done, let us now see the java program for matrix multiplication, followed by the explanation of the code.
Matrix multiplication program in Java
MatrixMultiplicationis class in which static method
multiplyMatrices()method contains the implementation for multiplying 2 matrices.
printMatrix()method simply prints the matrix in a pretty format as rows and columns.
- In the
main()method, first 2 matrices –
m2– are defined as 2-dimensional
intarrays. The arrays are initialized during definition with
m1having 2 rows and 3 columns, and
m2having 3 rows and 3 columns.
m2are then sent as parameters to
multiplyMatrices()method, where the matrices are received into parameters named
multiplyMatrices()– first the mandatory condition for matrix multiplication is checked. I.e. whether matrix1’s number of columns is same as matrix2’s number of rows. If not – an error is thrown and matrix multiplication is skipped with a
nullvalue being returned.
- The actual logic for matrix multiplication is inside 3 nested loops. The outermost loop is for rows, the middle loop is for columns and the innermost loop sums together the products of correponding row and column elements as explained via the matrix multiplication formula and example above.
- The matrix
product, which is a matrix of 2 rows and 3 colums is sent back as the return value to the
main()method where it is printed, using
printMatrix()method, along with the two matrices which were multiplied, in the M X N = MN format.