Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Create a Class That Performs Matrix Multiplication via a Custom Method

Python Create a Class That Performs Matrix Multiplication via a Custom Method

Document Object Reference Manual Python3 Examples

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

]

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

)

print

(

result_matrix

)

Code analysis:

  1. __init__ method is used to initialize the matrix object, accepting a 2D list data as a parameter and computing the number of rows and columns of the matrix.
  2. multiply method 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.
  3. __str__ method is used to convert the matrix object to string form for convenient printing.
  4. Two matrices are created in the example matrix1 and matrix2and call the multiply method for matrix multiplication, and finally print the result.

Output result:

58 64
139 154

Document Object Reference Manual Python3 Examples