Python Create a Class That Performs Matrix Multiplication via a Custom Method
We will create a class named Matrix class that contains a custom method multiplyused to perform matrix multiplication. Matrix multiplication requires that the number of columns of the first matrix equals the number of rows of the second matrix.
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
multiply
(
self
,
other
)
:
if
self
.
cols
!=
other.
rows
:
raise
ValueError
(
"The number of columns in the first matrix must be equal to the number of rows in the second matrix."
)
result
=
[
[
0
for
_
in
range
(
other.
cols
)
]
for
_
in
range
(
self
.
rows
)
]
for
i
in
range
(
self
.
rows
)
:
for
j
in
range
(
other.
cols
)
:
for
k
in
range
(
self
.
cols
)
:
result
[
i
]
[
j
]
=
self
.
data
[
i
]
[
k
]
- other.
data
[
k
]
[
j
]
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
]
]
)
matrix2
=
Matrix
(
[
[
7
,
8
]
,
[
9
,
10
]
,
[
11
,
12
]
]
)
result_matrix
=
matrix1.
multiply
(
matrix2
)
(
result_matrix
)
Code analysis:
__init__method is used to initialize the matrix object, accepting a 2D listdataas a parameter and computing the number of rows and columns of the matrix.multiplymethod is used to perform matrix multiplication. First check whether the number of columns of the first matrix equals the number of rows of the second matrix; if not, raise an exception. Then create a result matrix and use a triple loop to compute the value of each element.__str__method is used to convert the matrix object to string form for convenient printing.- Two matrices are created in the example
matrix1andmatrix2and call themultiplymethod for matrix multiplication, and finally print the result.
Output result:
58 64
139 154
Python3 Examples