Multiply Two Matrices In Java

By bhagwatchouhan
Multiply Two Matrices In Java

This tutorial provides the Matrix Multiplication program in Java to multiply two matrices using multi-dimensional arrays.

 

Steps required to Multiply the Matrices

 

Step 1 - Construct the two arrays to store the values of the matrices.

 

Step 2 - Make sure that the matrices are compatible with each other i.e. the number of rows in the first matrix is equal to the columns in the second matrix and the number of columns in the first matrix is equal to the number of rows in the second matrix.

 

Step 3 - Create the resultant matrix having rows equal to the rows of the first matrix and columns equal to the columns of the second matrix.

 

Step 4 - Traverse each element of the two matrices and multiply them and store the result in the resultant matrix.

 

The Program and Result - Three Rows & Three Columns

 

Below mentioned is the program to multiply two matrices in Java using three rows and three columns.

 

public class MatrixMultiplication {

public static void main( String args[] ) {

// Declare and Construct the matrices
// three rows and three columns
int matrixA[][] = { {1,5,2}, {2,1,3}, {4,2,1} };
int matrixB[][] = { {2,3,6}, {4,6,8}, {3,6,1} };

// Declare and Construct the resultant matrix
// three rows and three columns
int result[][] = new int[3][3];

// Outer Loop
for( int i = 0; i < 3; i++ ) {

// Inner Loop
for( int j = 0; j < 3; j++ ) {

result[ i ][ j ] = 0;

// Multiplication
for( int k = 0; k < 3; k++ ) {

result[ i ][ j ] += matrixA[ i ][ k ] * matrixB[ k ][ j ];
}

// Print
System.out.print( result[ i ][ j ] + " " );
}

System.out.println();
}
}
}

 

The result of the multiplication is shown below.

 

// Result
28 45 48
17 30 23
19 30 41

 

The Program and Result - N Rows & M Columns

 

Below mentioned is the program to multiply two matrices in Java using n rows and m columns.

 

public class MatrixMultiplication {

public static void main( String args[] ) {

int rows1 = 2;
int cols1 = 3;
int rows2 = 3;
int cols2 = 2;

// Declare and Construct the matrices
int matrixA[][] = { {1,5,2}, {2,1,3} };
int matrixB[][] = { {2,3}, {4,6}, {3,6} };

// Declare and Construct the resultant matrix
int result[][] = new int[ rows1 ][ cols2 ];

// Outer Loop
for( int i = 0; i < rows1; i++ ) {

// Inner Loop
for( int j = 0; j < cols2; j++ ) {

result[ i ][ j ] = 0;

// Multiplication
for( int k = 0; k < rows2; k++ ) {

result[ i ][ j ] += matrixA[ i ][ k ] * matrixB[ k ][ j ];
}

// Print
System.out.print( result[ i ][ j ] + " " );
}

System.out.println();
}
}
}

 

The result of the multiplication is shown below.

 

// Result
28 45
17 30

 

Summary

 

This tutorial provided the program to multiply two matrices in java using multi-dimensional arrays.

Share this blog:

Profile picture for user bhagwatchouhan
bhagwatchouhan