2014-02-12 2 views
0

숫자가 많은 입력 배열에서 작동 할 수있는 임의의 수의 간격과 함수로 조각 별 함수를 작성해야합니다.임의의 길이의 엄청난 조각

아래 코드 스 니펫에서 볼 수 있듯이 for 루프 및 표시기 배열을 사용하여 수행 할 수 있지만 더 파이썬 적 방법이 있습니까?

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() 

답변

1

당신은 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])이 호출 코드로 이동됩니다.

+1

완벽하게 작동합니다. 빠른 답변 주셔서 감사합니다! – Francesco

관련 문제