Python Practice Example 44 - Python Addition of Two Matrices
Given two 3-row, 3-column matrices, add the data at their 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 3-row, 3-column matrix, use a for loop to iterate and retrieve the values at corresponding positions in matrices X and Y, add them, and place the results at the corresponding positions in 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 and output rows
for
i
in
range
(
len
(
X
)
)
:
Iterate and output columns
for
j
in
range
(
len
(
X
[
0
]
)
)
:
result
[
i
]
[
j
]
=
X
[
i
]
[
j
]
Y
[
i
]
[
j
]
for
r
in
result
:
(
r
)
After executing the above code, the output is as follows:
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]
Python 100 Examples