我正在修模糊系统的课程,我在电脑上修my notes。这意味着我必须不时地在电脑上画图表。由于这些图定义得很好,我觉得用numpy
绘制它们是个好主意(我用LaTeX做笔记,而且我在python shell上很快,所以我想我可以摆脱这个)。
fuzzy membership functions的图形是高度分段的,例如:
的数据
为了绘制这个图,我尝试了numpy.piecewise
的以下代码(这给了我一个神秘的错误):
In [295]: a = np.arange(0,5,1)
In [296]: condlist = [[b<=a<b+0.25, b+0.25<=a<b+0.75, b+0.75<=a<b+1] for b in range(3)]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-296-a951e2682357> in <module>()
----> 1 condlist = [[b<=a<b+0.25, b+0.25<=a<b+0.75, b+0.75<=a<b+1] for b in range(3)]
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [297]: funclist = list(itertools.chain([lambda x:-4*x+1, lambda x: 0, lambda x:4*x+1]*3))
In [298]: np.piecewise(a, condlist, funclist)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-298-41168765ae55> in <module>()
----> 1 np.piecewise(a, condlist, funclist)
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/lib/function_base.pyc in piecewise(x, condlist, funclist, *args, **kw)
688 if (n != n2):
689 raise ValueError(
--> 690 "function list and condition list must be the same")
691 zerod = False
692 # This is a hack to work around problems with NumPy's
ValueError: function list and condition list must be the same
字符串
在这一点上,我相当困惑如何绘制这个函数。我真的不理解错误消息,这进一步阻碍了我调试它的努力。
最后,我希望绘制并导出到EPS文件中的这个函数,所以我也很感激沿着这些路线的任何帮助。
1条答案
按热度按时间jljoyd4f1#
一般来说,numpy数组非常擅长做一些明智的事情,当你只是把它们当作数字来写代码时。链接比较是一个罕见的例外。您看到的错误基本上是这样的(由于
piecewise
内部和ipython错误格式而有点模糊):字符串
您也可以使用
np.logical_and
,但按位的&
(不是and
)在这里工作得很好。就绘图而言,numpy本身不做任何事情。下面是一个matplotlib的例子:
型
请注意,
piecewise
是一个反复无常的野兽。特别是,它需要它的x
参数是一个数组,如果不是,甚至不会尝试转换它(用numpy
的说法:x
必须是ndarray
,而不是array_like
):型