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

Python Write a Program to Implement Matrix Multiplication

Python Write a Program to Implement Matrix Multiplication

Document Object Reference Manual Python3 Examples

Matrix multiplication is a basic operation in linear algebra. Given two matrices A and B, the result of matrix multiplication is a new matrix C, where each element of C is the dot product of the corresponding row of A and the corresponding column of B. Suppose A is an m×n matrix and B is an n×p matrix; then the result matrix C will be an m×p matrix.

Example

def

matrix_multiply

(

A

,

B

)

:

   

Get the dimensions of matrices A and B

    rows_A

=

len

(

A

)

    cols_A

=

len

(

A

[

0

]

)

    rows_B

=

len

(

B

)

    cols_B

=

len

(

B

[

0

]

)

   

Check whether the number of columns of matrix A equals the number of rows of matrix B

   

if

cols_A

!=

rows_B:

       

raise

ValueError

(

"The number of columns of matrix A must equal the number of rows of matrix B"

)

   

Initialize the result matrix C with size rows_A x cols_B

    C

=

[

[

0

for

_

in

range

(

cols_B

)

]

for

_

in

range

(

rows_A

)

]

   

Perform matrix multiplication

   

for

i

in

range

(

rows_A

)

:

       

for

j

in

range

(

cols_B

)

:

           

for

k

in

range

(

cols_A

)

:

                C

[

i

]

[

j

]

=

A

[

i

]

[

k

]

[

k

]

[

j

]

   

return

C

Example matrices

A

=

[

[

1

,

2

,

3

]

,

     

[

4

,

5

,

6

]

]

B

=

[

[

7

,

8

]

,

     

[

9

,

10

]

,

     

[

11

,

12

]

]

Call the matrix multiplication function

result

=

matrix_multiply

(

A

,

B

)

Output result

for

row

in

result:

   

print

(

row

)

Code analysis:

  1. matrix_multiply The function accepts two matrices A and B as input.
  2. First get the dimensions of matrices A and B, and check whether the number of columns of A equals the number of rows of B; if not, raise an error.
  3. Initialize the result matrix C with size rows_A x cols_B, with all elements initialized to 0.
  4. Use a triple loop for the matrix multiplication: the outer loop iterates over the rows of A, the middle loop over the columns of B, and the inner loop computes the dot product and accumulates it at the corresponding position in C.
  5. Finally, return the result matrix C.

Output result:

[58, 64]
[139, 154]

Document Object Reference Manual Python3 Examples