Python Implement a Class-Based Matrix Class
We will create a class-based matrix class that supports matrix initialization, matrix addition, matrix multiplication, and matrix transposition. This class will help us understand how to use classes in Python to encapsulate data and operations.
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
mul
(
self
,
other
)
:
if
self
.
cols
!=
other.
rows
:
raise
ValueError
(
"Number of columns in the first matrix must be equal to the number of rows in the second matrix."
)
result
=
[
[
sum
(
self
.
data
[
i
]
[
k
]
- other.
data
[
k
]
[
j
]
for
k
in
range
(
self
.
cols
)
)
for
j
in
range
(
other.
cols
)
]
for
i
in
range
(
self
.
rows
)
]
return
Matrix
(
result
)
def
transpose
(
self
)
:
result
=
[
[
self
.
data
[
j
]
[
i
]
for
j
in
range
(
self
.
rows
)
]
for
i
in
range
(
self
.
cols
)
]
return
Matrix
(
result
)
def
str
(
self
)
:
return
'n'
.
join
(
[
' '
.
join
(
map
(
str
,
row
)
)
for
row
in
self
.
data
]
)
Example usage
m1
=
Matrix
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
m2
=
Matrix
(
[
[
5
,
6
]
,
[
7
,
8
]
]
)
(
"Matrix 1:"
)
(
m1
)
(
"Matrix 2:"
)
(
m2
)
(
"Matrix 1 + Matrix 2:"
)
(
m1 + m2
)
(
"Matrix 1 * Matrix 2:"
)
(
m1 * m2
)
(
"Transpose of Matrix 1:"
)
(
m1.
transpose
(
)
)
Code analysis:
__init__method is used to initialize the matrix object, accepting a 2D list as a parameter and computing the number of rows and columns of the matrix.__add__method implements matrix addition; first it checks whether the two matrices have the same dimensions, then adds the elements one by one and returns a new matrix object.__mul__method implements matrix multiplication; first it checks whether the number of columns of the first matrix equals the number of rows of the second matrix, then performs the matrix multiplication and returns a new matrix object.transposemethod implements matrix transposition, returning a new transposed matrix object.__str__method is used to convert the matrix object to string form for convenient printing.
Output result:
Matrix 1:
1 2
3 4
Matrix 2:
5 6
7 8
Matrix 1 + Matrix 2:
6 8
10 12
Matrix 1 * Matrix 2:
19 22
43 50
Transpose of Matrix 1:
1 3
2 4
Python3 Examples