Python matplotlib 值错误 : The truth value of an array with more than one element is ambiguous

标签 python matlab matplotlib plot

我正在尝试使用 matplotlib 和 python 绘制两个函数 func1 和 func2。我不断收到以下代码的 ValueError 错误,但不知道出了什么问题。我搜索了相关问题,尝试了很多东西,但似乎没有任何效果。

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 1)
plt.xlim(0, 10)
plt.ylim(0, 10)
plt.xlabel('$X$')
plt.ylabel('$Outputs$')
plt.title('Title')

x = np.arange(0, 10, .1)

def func1(X):
    output = max(3*X/7 - 3/7, 0, 12*X/35 - 3/35)
    return output

def func2(X):
    output = max(3*X/7 - 3/7, 0)
    return output

plt.plot(x, func1(x), 'g')
plt.plot(x , func2(x), 'b')

plt.show()

最佳答案

max(2,3) 显然是 3,因为 3 > 2

但是当我们比较 ndarray 参数时,我们得到的不是单个标量结果,而是一个数组:

In [23]: np.array([3,1]) > np.array([1,2])
Out[23]: array([ True, False], dtype=bool)

我们无法将 bool 数组转换为单个值——它应该是 True,因为至少有一个,还是 False,因为它不全是 True?或者,正如错误消息所说,“具有多个元素的数组的真值不明确”。这意味着内置 max 函数会失败,因为它尝试根据比较是否正确进行分支。

幸运的是,因为看起来你想要成对最大值,numpy 已经有一个函数可以处理这个问题,np.maximum 。将代码中的内置 max 替换为 np.maximum 可以得到:

working graph

关于Python matplotlib 值错误 : The truth value of an array with more than one element is ambiguous,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42101986/

相关文章:

python - 合并排序实现以按字符串长度排序 - python

python 在没有正则表达式的情况下在多个分隔符上拆分字符串

java - 使用 javaaddpath 将 java 库添加到 MATLAB 中

Matlab矩阵乘法和转置精度

python - 使用 set_yticklabels 会产生水平对齐的刻度标签,而不是垂直对齐

python - 在同一轴python上绘制for循环内生成的多个图

python - NLTK 将树转换为数组?

python - 在不关心 ssh session 的情况下在远程主机上运行脚本

python - 如何在 Django 中调用 "MATLAB engine for Python"?

python - matplotlib 和 seaborn 热图在 Jupyter 中与 savefig 的渲染方式不同(标签被切断)