# Matrix multiplication in Python

Matrix Multiplication without using any built-in functions
``````rows=2
cols=3
M1=[[1,2,3],
[4,5,6]]
M2=[[7,8],
[9,10],
[11,12]]
my_list=[]

for  l_row in range(0,rows):
temp_list=[]
for k in range(0,rows):
sum1=0
for l_col in range(0,cols):
sum1=sum1+(M1[l_row][l_col]*M2[l_col][k])

temp_list.append(sum1)
my_list.append(temp_list)
for row in my_list:
print(row)``````
Output is here
``````[58, 64]
[139, 154]``````
We can generate Matrix by using random numbers
``````from random import randrange
rows=4
cols=4
M1=[]
M2=[]
for j in range(0,rows):
temp1=[]
for k in range(0,cols):
x=randrange(10)
temp1.append(x)
#print(x)
M1.append(temp1)
print(M1)
print("M1 shown above ")

for j in range(0,cols):
temp1=[]
for k in range(0,rows):
x=randrange(10)
temp1.append(x)
M2.append(temp1)
print(M2)
print('M2 is shown above ')
my_list=[]

for  l_row in range(0,rows):
temp_list=[]
sum1=0
for k in range(0,rows):
sum1=0

for l_col in range(0,cols):
sum1=sum1+(M1[l_row][l_col]*M2[l_col][k])
temp_list.append(sum1)
my_list.append(temp_list)
for row in my_list:
print(row)``````
Output
``````[[3, 3, 8, 3], [0, 3, 8, 0], [3, 5, 4, 7], [7, 5, 6, 9]]
M1 shown above
[[4, 5, 1, 2], [5, 6, 3, 6], [9, 7, 3, 2], [8, 4, 1, 6]]
M2 is shown above
[123, 101, 39, 58]
[87, 74, 33, 34]
[129, 101, 37, 86]
[179, 143, 49, 110]``````
Using Numpy library we can check our code. Just add these lines at the end of the above code.
``````print("Using Numpy and checking result")
import numpy as np
res = np.dot(M1,M2)
print(res)``````

Subscribe to our YouTube Channel here

## Subscribe

* indicates required
Subscribe to plus2net

plus2net.com