# Multiplying two matrices using Python

In this tutorial, we will be solving multiplication of two matrices in the Python.

## Matrix Multiplication of two Matrices in Python

In Python, we will implement a matrix as a nested list.

We can treat each element as a row of the matrix.

For example X=[[1,2], [3,4], [5,7]] would represent a 3×2 matrix. The first row can be selected as X[0] and the element in the first row, the first column can be selected as x[0][0].

Multiplication of two matrices X and Y is defined only if the number of columns in `X` is equal to the number of rows `Y`.or else it will lead to an error in the output result.

If X is a (n X m) matrix and Y is a (m x 1) matrix then, XY is defined and has the dimension (n x 1).

You can also read:

- How to Perform Matrix Multiplication of given dimension in Python
- How to create matrix of random numbers in Python – NumPy

### Program to multiply two matrices in Python

follow the given below code to implement matrics operation between two matrices.

# 3x3 matrix X = [[1,3,2], [3 ,6,8], [5 ,2,1]] # 3x3 matrix Y = [[6,8,6], [6,3,3], [2,5,1]] # result is 3x4 result = [[0,0,0], [0,0,0], [0,0,0]] # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r)

hence this will result in the following output

[28, 27, 17] [70, 82, 44] [44, 51, 37]

congratulation, you have completed and learn how to multiply two matrices in python

#### Conclusion

In this tutorial, we have learned the following

- what is python
- multiplication of two matrices
- implementation in python script

Hope you got a fair idea about the multiplication of matrix in addition to this we will be covering multiplication of matric using NumPy.

## Leave a Reply

You must be logged in to post a comment.