Explanation
In this program, we need to multiply two matrices and print the resulting matrix.
Product of two matrices
The product of two matrices can be computed by multiplying elements of the first row of the first matrix with the first column of the second matrix then, add all the product of elements. Continue this process until each row of the first matrix is multiplied with each column of the second matrix
Consider above example, first element in resulting matrix prod[0,0] can be computed by multiplying first row of first matrix i.e. (1, 3, 2) with first column of second matrix i.e. (2, 1, 1) and finally sum all the product of elements i.e. (1*2) + (3*1) + (2*1) = 7. Similarly, second entry prod[0,1] can be computed by multiplying the first row of the first matrix with the second column of the second matrix and sum all the product.
Two matrices can be multiplied if and only if they satisfy the following condition:
the number of columns present in the first matrix should be equal to the number of rows present in the second matrix.
Suppose dimension of matrix A is p × q and matrix B is q × r, then the dimension of resulting matrix will be p × r. Matrix multiplication can be represented as
Cij = Σ AikBkj
Algorithm
- Declare and initialize two two-dimensional arrays a and b.
- Calculate the number of rows and columns present in the array a and store it in variables row1 and col1 respectively.
- Calculate the number of rows and columns present in the array b and store it in variables row2 and col2 respectively.
- Check if col1 is equal to row2. For two matrices to be multiplied, the number of column in the first matrix must be equal to the number of rows in the second matrix.
- If col1 is not equal to row2, display the message "Matrices cannot be multiplied."
- If they are equal, loop through the arrays a and b by multiplying elements of the first row of the first matrix with the first column of the second matrix and add all the product of elements.
e.g prod11 = a11 x b11 + a11 x b21 + a11 x b31
- Repeat the previous step till all the rows of the first matrix is multiplied with all the columns of the second matrix.
- Display the elements of array prod.
Input:
Matrix a = [1, 3, 2]
[3, 1, 1]
[1, 2, 2]
matrix b = [2, 1, 1]
[1, 0, 1]
[1, 3, 1]
Output:
Product of two matrices: [7 7 6]
[8 6 5]
[6 7 5]
Python
Output:
C
Output:
JAVA
Output:
C#
Output:
PHP
Output: