Python Write a Program to Implement Matrix Multiplication
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
]
- B
[
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:
(
row
)
Code analysis:
matrix_multiplyThe function accepts two matrices A and B as input.- 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.
- Initialize the result matrix C with size
rows_A x cols_B, with all elements initialized to 0. - 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.
- Finally, return the result matrix C.
Output result:
[58, 64]
[139, 154]
Python3 Examples