![]() |
VOOZH | about |
Matrices are multidimensional arrays that store data in the form of Rows and columns. Perl allows performing various operations on these matrices like Addition, Subtraction, Division, and Multiplication. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++.
Given are two matrices, the task is to multiply them. Matrices can either be square or rectangular.
Example:
Input : mat1[][] = {{2, 4},
{3, 4}}
mat2[][] = {{1, 2},
{1, 3}}
Output : {{6, 16},
{7, 18}}
Firstly, the user has to provide the dimensions of the two matrices with the help of <STDIN>.
In order to multiply two matrices, the number of columns in the first matrix must be equal to the number of rows in the second matrix. To check if the matrices are multiplicative if-else conditional loop is used in the code.
Now if the above condition is not fulfilled then we know that we have to implement matrix multiplication in our else condition and for that, we will first take the values inside the two matrices with the help of nested-for loops. First for loop will be used to change the row and the second one will be used to access all columns in that particular row.
After this, the multiplication process is done in which ith column of the first matrix is multiplied with jth row of the second matrix and the respective products are added to find out the value at [i][j] position of the product matrix. For executing this, three nested loops are used in the code as follows:
In the above-written code, a temporary variable(temp) is initiated as 0. After the multiplication of ith column of the first matrix and jth row of the second matrix the product is added to the temp, in this way we will be able to add all the products found out by multiplying two numbers at a time. Here the for loop of variable $g is helping us in accessing all the positions of the two previously defined matrices. To understand the logic consider that for matrix 1 we are fixing the column with i and then moving to various rows using 'g' and in matrix 2 we are fixing the row with j and then change column using g. As we know that $b = $c, it doesn't matter whether $g goes from 0 to $b or from 0 to $c. Finally, we put the value in temp to its respective position and put temp again to 0 and find value on the other positions. This will result in the formation of a product matrix that was required.
Following is the final code to perform the process of matrix multiplication:
Output:
👁 Multiplication of matrices