[英]how do I make a numpy.piecewise function of arbitrary length? (having lambda issues)
[英]Numpy piecewise of arbitrary length
我需要構建一個具有任意數量的間隔和函數的分段函數,該函數可以對輸入的numpy數組進行操作。
我可以使用for循環和指標數組來做到這一點,如下面的代碼片段所示,但是還有更多的Python方式可以做到這一點嗎?
我嘗試使用numpy.piecewise,但據我所知,段和函數的數量需要在源代碼中靜態定義。
import numpy as np
import matplotlib.pyplot as plt
# inputs:
# -xs: points in which to compute the piecewise function
# -segments: the extremes of the piecewise intervals (as a list)
# -funcs: the functions (as a list; len(funcs)==len(segments)-1 )
def calc_piecewise(xs, segments, funcs):
# prepare indicators and results arrays
indaseg = np.zeros(len(xs), np.bool)
ys = np.zeros_like(xs)
# loop through intervals and compute the ys
for ii in range(len(funcs)):
indaseg = np.logical_and(xs>=segments[ii], xs<=segments[ii+1])
ys[indaseg] = funcs[ii](xs[indaseg])
return ys
def test_calc_piecewise():
segments = [0.0, 1.0, 2.5, 4.0, 5.0]
def f0(xs):
return xs
def f1(xs):
return xs*xs
def f2(xs):
return 12.5-xs*xs
def f3(xs):
return 4.0*xs-19.5
funcs = [f0, f1, f2, f3]
xs = np.linspace(0.0, 5.0, 500)
ys = calc_piecewise(xs, segments, funcs)
plt.figure()
title = "calc_piecewise"
plt.title(title)
plt.plot(xs, ys, 'r-')
plt.show()
return
test_calc_piecewise()
您可以按如下方式使用np.piecewise
(為格式化np.piecewise
抱歉!):
ys = np.piecewise(
xs,
[(xs >= segments[i]) & (xs <= segments[i+1]) for i in range(len(segments)-1)],
funcs)
結果是一樣的。
本質上,您的循環和等效於indaseg = np.logical_and(xs>=segments[ii], xs<=segments[ii+1])
被移到調用代碼中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.