1# input two matrices of size n x m
2matrix1 = [[12,7,3],
3 [4 ,5,6],
4 [7 ,8,9]]
5matrix2 = [[5,8,1],
6 [6,7,3],
7 [4,5,9]]
8
9res = [[0 for x in range(3)] for y in range(3)]
10
11# explicit for loops
12for i in range(len(matrix1)):
13 for j in range(len(matrix2[0])):
14 for k in range(len(matrix2)):
15
16 # resulted matrix
17 res[i][j] += matrix1[i][k] * matrix2[k][j]
18
19print (res)
20
1# Program to multiply two matrices using nested loops
2
3# 3x3 matrix
4X = [[12,7,3],
5 [4 ,5,6],
6 [7 ,8,9]]
7# 3x4 matrix
8Y = [[5,8,1,2],
9 [6,7,3,0],
10 [4,5,9,1]]
11# result is 3x4
12result = [[0,0,0,0],
13 [0,0,0,0],
14 [0,0,0,0]]
15
16# iterate through rows of X
17for i in range(len(X)):
18 # iterate through columns of Y
19 for j in range(len(Y[0])):
20 # iterate through rows of Y
21 for k in range(len(Y)):
22 result[i][j] += X[i][k] * Y[k][j]
23
24for r in result:
25 print(r)
26
1>>> a = np.array([[ 5, 1 ,3],
2 [ 1, 1 ,1],
3 [ 1, 2 ,1]])
4>>> b = np.array([1, 2, 3])
5>>> print a.dot(b)
6array([16, 6, 8])