Python Exercise Example 44 - Adding Two Matrices in Python
Two 3x3 matrices. Add the data at corresponding positions and return a new matrix:
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
Program analysis: Create a new 3x3 matrix, use a for loop to iterate and take out the values at corresponding positions in matrices X and Y, add them, and place them into the corresponding positions of the new matrix.
Program source code:
Source Code:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# Iterate over rows
for i in range(len(X)):
# Iterate over columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
Executing the above code, the output is as follows:
[17, 15, 4] [10, 12, 9] [11, 13, 18]Other extensions
Python 100 Examples