1num = [2, 3, 4], [5, 6, 7]
2num2 = [8, 9, 10], [11, 12, 13]
3num3 = [0, 0, 0], [0, 0, 0]
4for i in range(len(num)):
5 print(num[i])
6for i in range(len(num)):
7 print(num2[i])
8print()
9for i in range (len(num)):
10 for j in range(len(num)+1):
11 num3[i][j] = num[i][j] + num2[i][j]
12
13for i in range(len(num3)):
14 print(num3[i])
1# Program to add two matrices using nested loop
2
3X = [[12,7,3],
4 [4 ,5,6],
5 [7 ,8,9]]
6
7Y = [[5,8,1],
8 [6,7,3],
9 [4,5,9]]
10
11result = [[0,0,0],
12 [0,0,0],
13 [0,0,0]]
14
15# iterate through rows
16for i in range(len(X)):
17 # iterate through columns
18 for j in range(len(X[0])):
19 result[i][j] = X[i][j] + Y[i][j]
20
21for r in result:
22 print(r)
23
1matrix1 = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
2matrix2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
3
4
5def addTheMatrix(matrix1, matrix2):
6 matrix1Rows = len(matrix1)
7 matrix2Rows = len(matrix2)
8 matrix1Col = len(matrix1[0])
9 matrix2Col = len(matrix2[0])
10
11 #base case
12 if(matrix1Rows != matrix2Rows or matrix1Col != matrix2Col):
13 return "ERROR: dimensions of the two arrays must be the same"
14
15 #make a matrix of the same size as matrix 1 and matrix 2
16 matrix = []
17 rows = []
18
19 for i in range(0, matrix1Rows):
20 for j in range(0, matrix2Col):
21 rows.append(0)
22 matrix.append(rows.copy())
23 rows = []
24
25 #loop through the two matricies and the summation should be placed in the
26 #matrix
27 for i in range(0, matrix1Rows):
28 for j in range(0, matrix2Col):
29 matrix[i][j] = matrix1[i][j] + matrix2[i][j]
30
31 return matrix
32
33
34
35print(addTheMatrix(matrix1, matrix2))
36#output = [[1, 3, 5], [7, 9, 11], [13, 15, 17]]
1# Program to add two matrices using list comprehension
2
3X = [[12,7,3],
4 [4 ,5,6],
5 [7 ,8,9]]
6
7Y = [[5,8,1],
8 [6,7,3],
9 [4,5,9]]
10
11result = [[X[i][j] + Y[i][j] for j in range(len(X[0]))] for i in range(len(X))]
12
13for r in result:
14 print(r)