【发布时间】:2020-03-12 11:35:30
【问题描述】:
我有一个矩阵 A 和 B,我想要这两个矩阵的乘积。这是我在 python 中的代码。
import numpy as np
def matrix_multiplication(a: np.ndarray, b: np.ndarray) -> np.ndarray:
n, m_a = a.shape
m_b, p = b.shape
c = np.zeros((n, p))
if m_a != m_b:
raise ValueError('Dimensions of the Matrix A and B are not compatable.')
else:
for i in range(len(0, a.shape)):
for j in range(len(0, a.shape[0])):
for k in range(0, len(b.shape)):
c += a[i][j] * b[j][k]
print(c)
return c
但是当我运行代码时,我得到“进程以退出代码 0 完成”而不是矩阵 C。这里可能有什么问题?
【问题讨论】:
-
len只接受一个参数,即要获取长度的项目。你想做的事:range(len(a.shape))。 (假设len(a.shape)实际上是有效的。)在进入循环之前,您应该尝试打印出您在for循环中使用的值。 -
最后两行的缩进是否与您正在运行的实际 Python 代码相匹配?看起来 print 和 return 语句是在循环的第一次迭代中到达的。
-
考虑到 n = A 的行,m_a = A 的列,m_b = B 的列,p = B 的行,for 循环在迭代所需值时应该是正确的,但是会不会是
c += a[i][j] * b[j][k]有问题?
标签: python arrays function matrix