Python Use a Class to Implement a Matrix Addition Program
We will use a Python class to implement a simple matrix addition program. Matrix addition requires the two matrices to have the same dimensions; we will create a Matrix class and implement the matrix addition method within it.
Example
class
Matrix:
def
init
(
self
,
data
)
:
self
.
data
=
data
self
.
rows
=
len
(
data
)
self
.
cols
=
len
(
data
[
0
]
)
if
self
.
rows
>
;
0
else
0
def
add
(
self
,
other
)
:
if
self
.
rows
!=
other.
rows
or
self
.
cols
!=
other.
cols
:
raise
ValueError
(
"Matrices must have the same dimensions for addition."
)
result
=
[
[
self
.
data
[
i
]
[
j
]
- other.
data
[
i
]
[
j
]
for
j
in
range
(
self
.
cols
)
]
for
i
in
range
(
self
.
rows
)
]
return
Matrix
(
result
)
def
str
(
self
)
:
return
'n'
.
join
(
[
' '
.
join
(
map
(
str
,
row
)
)
for
row
in
self
.
data
]
)
Example usage
matrix1
=
Matrix
(
[
[
1
,
2
,
3
]
,
[
4
,
5
,
6
]
,
[
7
,
8
,
9
]
]
)
matrix2
=
Matrix
(
[
[
9
,
8
,
7
]
,
[
6
,
5
,
4
]
,
[
3
,
2
,
1
]
]
)
result_matrix
=
matrix1 + matrix2
(
result_matrix
)
Code analysis:
__init__method: initialize the matrix object, accepting a 2D listdataas input, and compute the number of rows and columns of the matrix.__add__method: implement matrix addition. First check whether the two matrices have the same dimensions; if not, raise an error. Then add elements one by one via a list comprehension to produce the resulting matrix.__str__method: convert the matrix to string form for convenient printing.
Output result:
10 10 10
10 10 10
10 10 10
Python3 Examples