【问题标题】:plot multivariate function based on max基于最大值绘制多元函数
【发布时间】:2022-11-04 05:46:12
【问题描述】:
我想创建一个多变量函数,该函数以2个功能的最大值,然后绘制它。但是,通过使用最大函数,在网格格里德上应用该函数时存在错误。我已经在没有最大功能的其他多元函数上尝试了此操作,并且它起作用。
import numpy as np
import pandas as pd
import plotly.graph_objects as go
def f(x,y):
return max(np.cos(x),np.sin(y))
x=np.linspace(0,5,20)
y=np.linspace(-3,2,20)
X, Y = np.meshgrid(x, y)
Z=f(X,Y)
fig = go.Figure(data=[go.Surface(x=X, y=Y, z=Z)])
fig.show()
我得到的错误是:The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()。但是,我认为该建议不适合我的情况。我还尝试使用 if 语句定义 max 函数,但正如我所料,我得到了同样的错误。有人可以帮忙吗?
【问题讨论】:
标签:
python
arrays
boolean
max
【解决方案1】:
np.sin 和 np.cos 函数与数组一起使用,max 函数会产生一个模棱两可的答案(你想要两个函数的最大值还是比较 - numpy 不知道)。我建议对数组中的每个值执行内置 math.sin, math.cos 并进行比较以获得所需的最大值。
def f(x,y):
max_values = []
for x_value, y_value in zip(x,y): #(iterate both together)
max_values.append(max(math.cos(x_value), math.sin(y_value)))
这可能比以前运行得慢,但这有帮助吗?
【解决方案2】:
尝试使用 ax.scatter3D
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
x=np.linspace(0,5,20)
y=np.linspace(-3,2,20)
def f(x,y):
max_values = []
for x_value, y_value in zip(x,y): #(iterate both together)
max_values.append(max(math.cos(x_value), math.sin(y_value)))
X, Y = np.meshgrid(x, y)
max_values = []
for x_value, y_value in zip(X,Y):
Z=zip([math.cos(item) for item in x_value],[math.sin(item) for item in y_value])
max_values.append([max(x,y) for x,y in Z])
fig = plt.figure()
ax = plt.axes(projection="3d")
ax.scatter3D(X, Y,max_values, c=max_values, cmap='Greens');
plt.show()