I would like to create a multivariate function that takes the max value of 2 functions and then to plot it. However by using the max function there is an error when applying the function on the meshgrid. I have tried this on other multivariate function without the max function and it worked.
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 error I get is : The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
. However, I don't think that the suggestion is adapted to my case. I also tried by defining the max function with if statement but as I expected I get the same error. Does anyone could help?
CodePudding user response:
The np.sin
and np.cos
functions work with arrays and the max
function would produce an ambiguous answer (do you want the maximum of both functions or a comparison - numpy
doesn't know). I recommend doing the built-in math.sin, math.cos
on each of the values in the arrays and compare to get the desired max value .
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)))
This may run slower than before, but does this help?
CodePudding user response:
try using ax.scatter3D with
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()