Matrix multiplication is a binary operation and it produces a matrix from two or more matrices. But for matrix multiplication the number of columns of the first matrix should be equal to the number of rows of the 2nd matrix.
Let the matrices be:
Where A and B are two given matrices which is to be multiplied and C is the resultant matrix were the result of the matrix multiplication.
The number of rows of C will be equal to the number of rows of the 1st matrix and the number of columns of the matrix C will be equal to the number of columns of the 2nd matrix.
For this example, A is a 2×2 matrix, B is also a 2×2 matrix, therefore, the resultant matrix C is also a 2×2 matrix. So, we will need 4 steps to get the result.
Step 1:
Step 2:
Step 3:
Step 4:
So, the matrix
INPUT: Two matrices
OUTPUT: The resultant matrix after multiplication.
PROCESS:
Step 1: [Taking the inputs]
Read r1, c1 [The number of rows and columns of the first matrix]
Read r2, c2 [The number of rows and columns of the second matrix]
If c1≠r2 then
Print "The matrix multiplication is not possible"
return
[End of ‘if’]
Print "Enter first matrix......"
For i=0 to r1-1 repeat
For j=0 to c1-1 repeat
Read a[i][j]
[End of ‘for’ loop]
[End of ‘for’ loop]
Print "Enter second matrix......."
For i=0 to r2-1 repeat
For j=0 to c2-1 repeat
Read b[i][j]
[End of ‘for’ loop]
[End of ‘for’ loop]
For i=0 to r1-1 repeat
For j=0 to c2-1 repeat
Set c[i][j]<-0
For k=0 to c1-1 repeat
Set c[i][j] <- c[i][j] + a[i][k] * b[k][j]
[End of ‘for’ loop]
[End of ‘for’ loop]
[End of ‘for’ loop]
[Printing the 3rd matrix after multiplication]
Print "After matrix multiplication....."
For i=0 to r1-1 repeat
For j=0 to c2-1 repeat
Print c[i][j]
[End of ‘for’ loop]
Move to the next line
[End of ‘for’ loop]
Step 3: Stop.
TIME COMPLEXITY:
for(i=0;i<r1;i++)------------------------- O(r1)
{ for(j=0;j<c2;j++)-------------- O(c2)
{
c[i][j]=0;--------------- O(1)
for(k=0;k<c1;k++) --- O(c1)
c[i][j] = c[i][j] + a[i][k] * b[k][j];--------- O(1)
}
}
The time complexity is O(r1*c2*c1). If the values of r1, c2, and c1 are the same then it can be defined as O().
Related
Contributed by