 # Multiplying two matrices in one line using Numpy in Python

Matrix multiplication — it is an operation that takes two matrices as input and creates one matrix by multiplying the rows of the first matrix by the column of the second matrix. In matrix multiplication, make sure that the number of rows in the first matrix must be equal to the number of columns in the second matrix.
Example: Multiplying two 3 × 3 matrices by each other

` Input: matrix1 = ([1, 2, 3], [3, 4, 5 ], [7, 6, 4]) matrix2 = ([5, 2, 6], [5, 6, 7], [7, 6, 4]) Output: [[36 32 32] [70 60 66] [93 74 100]] `

Methods for multiplying two matrices in python
1. Using an explicit for: loop is simple a matrix multiplication method, but one of the expensive methods for a large set of inputs. In this we use nested for loops to iterate over each row and each column.
If Matrix1 matrix is ​​ pCht and matrix2 is matrix MXL.

` `

``` # enter two matrices nxm matrix1 = [[ 12 , 7 , 3 ],   [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]] matrix2 = [[ 5 , 8 , 1 ],   [ 6 , 7 , 3 ], [ 4 , 5 , 9 ]]   res = [[ 0 for x in range ( 3 )] for y in range ( 3 )]    # explicit for loops for i in range ( len (matrix1)):   for j in range ( len (matrix2 [ 0 ])):   for k in range ( len (matrix2)):   # given matrix res [i] [j] + = matrix1 [i] [k] * matrix2 [k] [j]   print (res) ```

` `

Output:

` [[114 160 60] [74 97 73] [119 157 112]] `

In this program we used nested for loops to compute a result that will iterate over all the rows and columns of the matrices, and finally accumulate the sum of the result as a result.
2. Using Numpy: Multiplication using Numpy is also known as vectorization, the main purpose of which is to reduce or eliminate the explicit use of for loops in the program, which makes calculations faster.
Numpy — it is building a package in python to handle and manipulate arrays. For large matrix operations, we use the numpy python package, which is 1000 times faster than a single iterative method.
 ` # We need to install NumPy in order to import it ` ` import ` ` numpy as np `   ` # enter two matrices ` ` mat1 ` ` = ` ` ([` ` 1 ` `, ` ` 6 ` `, ` ` 5 ` `], [` ` 3 ` `, ` ` 4 ` `, ` ` 8 ` `], [` ` 2 ` `, 12 , 3 ] ) ```` mat2 = ([ 3 , 4 , 6 ], [ 5 , 6 , 7 ], [ 6 , 56 , 7 ])   # This will return a dot product res = np.dot (mat1, mat2)    # printing the given matrix print (res) ```
` [[63 320 83] [77 484 102] [84 248 117]] `