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 where 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, and 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 c2-1 repeat
Set c[i][j]<-0
[End of ‘for’ loop]
[End of ‘for’ loop]
Call the function multiply(a,r1, c1, b,r2, c2, c)
Step 2: [Function ‘multiply(a,r1, c1, b,r2, c2, c)’]
Set i <- 0, j <- 0, k <- 0
if i ≥ r1 then
return
else if i < r1 then
if j < c2 then
if k < c1 then
Set c[i][j]<-c[i][j] + a[i][k] * b[k][j]
Set k<-k+1
Call multiply(a,r1, c1, b,r2, c2, c)
[End of ‘if’]
Set k <- 0
Set j<-j+1
Call multiply(a,r1, c1, b,r2, c2, c);
[End of ‘if’]
Set j <- 0
Set i<-i+1
Call multiply(a,r1, c1, b,r2, c2, c);
[End of ‘if’]
[End of function ‘multiply(a,r1, c1, b,r2, c2, c)’]
Step 3: Stop.
Related
Contributed by