大话西游666
错误消息告诉您numpy.dot不知道如何处理 (1x1) 矩阵和 (4x1) 矩阵。但是,由于在您的公式中您只说要相乘,我假设您只想将标量乘积 (a,b) 中的标量与矩阵向量乘积中的向量相乘(嘛)。为此,您可以简单地*在 python 中使用。所以你的例子是:import numpy.matlib import numpy as np def complicated_matrix_function(M, a, b): ans1 = np.dot(a, b) ans2 = np.dot(M, a.T) out = ans1 * ans2 return out M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) a = np.array([[1, 1, 0]]) b = np.array([[-1], [2], [5]]) ans = complicated_matrix_function(M, a, b) print(ans) print() print("The size is: ", ans.shape)导致[[ 3] [ 9] [15] [21]]The size is: (4, 1)笔记请注意,这numpy.dot将做很多事情interpretation来弄清楚你想要做什么。因此,如果您不需要您的结果大小为 (4,1),您可以将所有内容简化为:import numpy.matlibimport numpy as npdef complicated_matrix_function(M, a, b): ans1 = np.dot(a, b) ans2 = np.dot(M, a) # no transpose required out = ans1 * ans2 return outM = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])a = np.array([1, 1, 0]) # no extra [] requiredb = np.array([-1, 2, 5]) # no extra [] requiredans = complicated_matrix_function(M, a, b)print(ans)print()print("The size is: ", ans.shape)导致[ 3 9 15 21]The size is: (4,)