Java Program to multiply two Matrix .
Objective
Write a Java program to multiply two matrices of compatible dimensions.
Algorithm / Approach
- Define dimensions for matrix 1 (3x2) and matrix 2 (2x4). The result matrix will be (3x4).
- Read input elements for both matrices using nested loops.
- Use three nested loops for multiplication. The outer two loops (i, j) traverse the resulting matrix
m3. - The innermost loop (k) performs the dot product of the i-th row of
m1and the j-th column ofm2. - Accumulate the sum:
sum = sum + m1[i][k] * m2[k][j]. - Assign
sumtom3[i][j]and resetsum = 0.
Matrix.java
import java.util.Scanner;
class Matrix {
void mul() {
Scanner s=new Scanner(System.in);
int r1 = 3, c1 = 2 ;
int r2 = 2, c2 = 4, sum =0;
int m1[][] = new int[r1][c1];
int m2[][] = new int[r2][c2];
int m3[][] = new int[r1][c2];
System.out.println("Enter Elements of Mat1: ");
for(int i = 0; i< r1; i++) {
for(int j = 0; j< c1; j++) {
m1[i][j] = s.nextInt();
}
}
System.out.println("Enter Elements of Mat2: ");
for(int i = 0; i< r2; i++) {
for(int j = 0; j< c2; j++) {
m2[i][j] = s.nextInt();
}
}
for(int i = 0; i< r1; i++) {
for(int j = 0; j< c2; j++) {
for(int k = 0; k< r2;k++) {
sum = sum+m1[i][k]*m2[k][j];
}
m3[i][j]= sum;
sum = 0;
}
}
System.out.println("Product of the matrix: ");
for(int i = 0; i< r1; i++) {
for(int j = 0; j< c2; j++) {
System.out.print(m3[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] a)
{
Matrix m = new Matrix();
m.mul();
}
}
Expected Output
Enter Elements of Mat1: 1 4 2 3 4 5 Enter Elements of Mat2: 1 2 3 4 1 3 4 5 Product of the matrix: 5 14 19 24 5 13 18 23 9 23 32 41
Explanation of the Program
- Matrix multiplication is much more complex than addition. You don't just multiply corresponding elements.
- Instead, you must calculate the dot product. To find the value for row 1, column 1 of the result, you multiply each element of row 1 in the first matrix by each corresponding element of column 1 in the second matrix, and add them all together.
- This requires three layers of nested loops, making it an expensive operation computationally.
Complexity
Time Complexity
O(r1 * c2 * c1) - Roughly O(N3) for square matrices.
Space Complexity
O(r1 * c2) - Memory required for the resulting matrix.
Common Mistakes
- Trying to multiply matrices with incompatible dimensions. The number of columns in the first matrix MUST equal the number of rows in the second matrix.