矩阵乘法 python
时间: 2023-11-26 07:48:26 浏览: 75
矩阵乘法是指两个矩阵相乘的运算,可以用Python实现。具体步骤如下:
1.定义两个矩阵A和B,其中A的列数等于B的行数。
```python
A = [[1, 2, 3], [4, 5, 6]]
B = [[7, 8], [9, 10], [11, 12]]
```
2.创建一个结果矩阵C,其行数等于A的行数,列数等于B的列数,初始化为0。
```python
C = [[0 for j in range(len(B[0]))] for i in range(len(A))]
```
3.遍历A的每一行和B的每一列,对应位置相乘并累加到结果矩阵C中。
```python
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j] += A[i][k] * B[k][j]
```
4.输出结果矩阵C。
```python
for row in C:
print(row)
```
完整代码如下:
```python
A = [[1, 2, 3], [4, 5, 6]]
B = [[7, 8], [9, 10], [11, 12]]
C = [[0 for j in range(len(B[0]))] for i in range(len(A))]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j] += A[i][k] * B[k][j]
for row in C:
print(row)
```
阅读全文