python - 在 Python 中使用带有矩阵函数的 numpy.meshgrid 时出错
问题描述
我想 3D 绘制使用多个矩阵运算的 af(x,y) 函数。我想寻找可能的最大值和最小值。这种矩阵运算的原因是有时这种类型的函数可以用更简洁、更紧凑的形式表示。但是,我在尝试修复一些错误时遇到了问题。在该函数 f(x,y) 的构造中,我必须将 2 维向量 (x,y) 转换为 (x,y,0) 或 (x,0,y) 形式的 3 维向量) 或 (0,x,y)。基本上错误来自使用这两种类型的功能:
功能一:
a = np.array([[1],
[3]])
def toy_function1(x,y):
u = np.asarray((x,y))
return np.matmul(u, a )
x = np.linspace(0, 5, 4)
y = np.linspace(0, 5, 3)
x, y = np.meshgrid(x,y)
z = toy_function1(x,y)
plt.contour(x, y, y, 20, cmap='RdGy');
有错误
ValueError Traceback (most recent call last)
<ipython-input-27-d1951bd0ff32> in <module>()
9 x, y = np.meshgrid(x,y)
10
---> 11 z = toy_function1(x,y)
12
13 plt.contour(x, y, y, 20, cmap='RdGy');
<ipython-input-27-d1951bd0ff32> in toy_function1(x, y)
3 def toy_function1(x,y):
4 u = np.asarray((x,y))
----> 5 return np.matmul(u, a )
6
7 x = np.linspace(0, 5, 4)
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 4)
功能二
a = np.array([[1],
[2],
[3]])
def toy_function2(x,y):
u = np.insert((x,y),0,0).reshape(1,3)
return np.matmul(u, a)
x = np.linspace(0, 5, 4)
y = np.linspace(0, 5, 3)
x, y = np.meshgrid(x,y)
z = toy_function2(x,y)
plt.contour(x, y, y, 20, cmap='RdGy');
有错误
ValueError Traceback (most recent call last)
<ipython-input-56-47a2104dff1b> in <module>()
13 x, y = np.meshgrid(x,y)
14
---> 15 z = toy_function2(x,y)
16
17 plt.contour(x, y, y, 20, cmap='RdGy');
<ipython-input-56-47a2104dff1b> in toy_function2(x, y)
5
6 def toy_function2(x,y):
----> 7 u = np.insert((x,y),0,0).reshape(1,3)
8 return np.matmul(u, a)
9
ValueError: cannot reshape array of size 25 into shape (1,3)
解决方案
推荐阅读
- docker - Docker端口冲突,即使没有绑定端口
- css - 全屏打印 MaterialUI 对话框
- gltf - 文件glTF中的角度单位是什么?
- css - 响应式设计 html 格格不入
- html - 如何在 991px 宽的平板电脑上强制使用 Bootstrap 中的汉堡菜单?
- regex - Kotlin 正则表达式空间有效,但字边界无效
- amazon-web-services - RDS 触发器的 Lambda 函数访问导致连接丢失
- python-3.x - 如何在文件中列出已通过所有考试的学生名单
- r - 有条件地将嵌套(字符)列表中的项目排序/变异到 R 中的新列中
- python - 在 beautifulsoup 的列表中使用 len 时,Python 'int' 对象不可迭代