Python Program to Multiply Two MatricesWe will write a Python program to get the multiplication of two input matrices and print the result in output. This Python program specifies how to multiply two matrices, having some certain values. Before writing the Python program, let's first look at the overview of the multiplication of two matrices. Matrix multiplicationMatrix multiplication is a binary operation that uses a pair of matrices to produce another matrix. The elements within the matrix are multiplied according to elementary arithmetic. In the multiplication of two matrices, the row elements of the first matrix are multiplied to the column elements of the second matrix. Example: Suppose we have given following two A and B matrices: C would be the addition of above given two matrices, i.e., C = A+B, and therefore C should be: As we can see that the resulting matrix C, which is also known as matrix product, has the same number of rows as the first matrix (A matrix) and the same number of columns as the second matrix (B matrix). We also know this type of multiplication of matrices as dot product of matrices. Multiplication of two matricesNow, we will write a Python program for the multiplication of two matrices where we perform the multiplication as we have performed in the abovegiven example. We can use various methods to write a Python program like this, but in this tutorial, we will only use the following two methods:
In both methods, we will write an example program to understand their implementation for multiplying two matrices. Method 1: Using nested for loop method:In this method, we are going to use nested for loop on two matrices and perform multiplication on them and store multiplication result in the third matrix as the result value. Let's understand implementation of this method through the following example. Example: Look at the following Python program: Output: The multiplication result of matrix A and B is: [37, 43, 59] [34, 58, 62] [58, 92, 103] Method 2: Using nested list comprehension method:In this method, we will use nested list comprehension to get the multiplication result of two input matrices. While using the list comprehension method in the program, we will also use 'zip in Python' on the nested list. Let's understand the implementation of this method through the following example. Example: Look at the following Python program: Output: The multiplication result of matrix A and B is: [37, 43, 59] [34, 58, 62] [58, 92, 103]
Next TopicPyhton Transpose Matrix
