包含多个元素的数组的真值不明确。使用a.any()或a.all()。在绘制三维图形时

2024-10-02 12:27:27 发布

您现在位置:Python中文网/ 问答频道 /正文

import numpy as np
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt

y = [4, 2]


def objectivedraw(a, b, y):
    return -1 * (y[0] + 0.75 * max((1 - b) * y[0] - (y[1] + a), 0) - 0.5 * max((y[1] + a) - (1 - b) * y[0], 0) \
                 + y[1] + 0.75 * max((1 - b) * y[1] - (y[0] + a), 0) - 0.5 * max((y[0] + b) - (1 - b) * y[1], 0))


a = np.arange(0, 3.0, 0.1)
b = np.arange(0, 1, 0.1)
A, B = np.meshgrid(a, b)  # grid of point
Z = objectivedraw(A, B,y)  # evaluation of the function on the grid

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
                       cmap=cm.RdBu, linewidth=0, antialiased=False)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

这是我正在使用的代码。与绘图相关的部分,即定义Z后,从https://dzone.com/articles/how-plot-function-two(网站上的第二块代码)开始处理。我收到一条错误消息:

File "C:/Users/rohan/PycharmProjects/untitled/plot utility.py", line 12, in objectivedraw + y[1] + 0.75 * max((1 - b) * y[1] - (y[0] + a), 0) - 0.5 * max((y[0] + b) - (1 - b) * y[1], 0)) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我想不出怎么修理它。我想这是因为我的功能

编辑:我想做一个费尔-施密特效用函数,这就是这个函数


Tags: offromimportplotmatplotlibasnpfig
1条回答
网友
1楼 · 发布于 2024-10-02 12:27:27

对于Z = objectivedraw(A, B, y)要使用AB作为(2D)numpy数组,并且Z也是一个numpy数组,函数objectivedraw应该与numpy兼容。在numpy中,数组上的函数是逐元素执行的,例如np.sin(A)将具有与A相同的元素数和维度数,但所有元素都被其正弦替换

@np.vectorize修饰符可以使函数矢量化。要与numpy兼容,max运算符应替换为np.maximum。而且,矢量化不知道如何处理列表y。在这种情况下y的元素可以逐个传递

import numpy as np
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt

@np.vectorize
def objectivedraw(a, b, y0, y1):
    return -1 * (y0 + 0.75 * np.maximum((1 - b) * y0 - (y1 + a), 0) - 0.5 * np.maximum((y1 + a) - (1 - b) * y0, 0)
                 + y1 + 0.75 * np.maximum((1 - b) * y1 - (y0 + a), 0) - 0.5 * np.maximum((y0 + b) - (1 - b) * y1, 0))

y = [4, 2]
a = np.arange(0, 3.0, 0.1)
b = np.arange(0, 1, 0.1)
A, B = np.meshgrid(a, b)  # grid of point
Z = objectivedraw(A, B, y[0], y[1])  # evaluation of the function on the grid

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(A, B, Z, rstride=1, cstride=1,
                       cmap=cm.RdBu, linewidth=0, antialiased=False)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

相关问题 更多 >

    热门问题