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

Python Use a Class to Implement a Matrix Addition Program

Python Use a Class to Implement a Matrix Addition Program

Document Object Reference Manual Python3 Examples

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

]

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

print

(

result_matrix

)

Code analysis:

  1. __init__ method: initialize the matrix object, accepting a 2D list data as input, and compute the number of rows and columns of the matrix.
  2. __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.
  3. __str__ method: convert the matrix to string form for convenient printing.

Output result:

10 10 10
10 10 10
10 10 10

Document Object Reference Manual Python3 Examples