Problem: Write a Java program to multiply two matrices and output the resultant matrix.
Example:
m1 = {{1, 2, 3}, {1, 1, 1}} m2 = {{1, 2}, {1, 3}, {1, 1}} m1*m2 = {{6, 11}, {3, 6}}
Two matrices A and B can only be multiplied, if the number of columns in A is equal to the number of rows in B and the order of the resultant matrix would be (rows of A x columns of B).
Knowing all this, we can multiply two matrix in Java as follows:
- Input
matrix1
andmatrix2
- Declare empty resultant matrix of order (r1, c2)
- Loop from 0 to
result.length
asi
:- Nest another loop from 0 to
result[0].length
asj
:- Nest another loop from 0 to
matrix1[0].length
ask
:- Sum
(matrix1[I][K] * matrix2[K][J])
- Sum
- Store the sum into the resultant matrix as
result[i][j]=sum
- Nest another loop from 0 to
- End loop.
- Nest another loop from 0 to
- End loop.
- Output the resultant matrix.
Here is the Java program that implements the above logic to multiply two matrices:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//matrix-I
int matrix1[][] = {{1, 2, 3},
{1, 1, 1}};
//matrix-II
int matrix2[][] = {{1, 2},
{1, 3},
{1, 1}};
//declare resultant matrix of order (1st.row x 2nd.col)
int result[][] = new int[2][2];
//matrix multiplication algorithm
for(int i=0; i<result.length; i++){
for(int j=0; j<result[0].length; j++){
int sum=0;
for(int k=0; k<matrix1[0].length; k++){
sum += matrix1[i][k]*matrix2[k][j];
}
result[i][j] = sum;
}
}
//display the resultant matrix
System.out.println("Resultant Matrix");
for(int i=0; i<result.length; i++){
for(int j=0; j<result[0].length; j++){
System.out.print(result[i][j]+ " ");
}
System.out.println();
}
}
}
Output:
Resultant Matrix
6 11
3 6