2010-12-18 110 views
4

當 輸入超出範圍時,我想通過用常數替換外推值來「修改」Mathematica的插值[]函數(在 維中)。Mathematica插值[]當超出範圍時保持不變

換句話說,如果插值域爲[1,20]和f [1] == 7和 F [20] == 12,我想:

f[x] = 7 for x<=1 
f[x] = 12 for x>=20 
f[x] = Interpolation[...] 

然而,這種失敗:

(* interpolation w cutoff *) 
interpcut[r_] := Module[{s, minpair, maxpair}, 

(* sort array by x coord *) 
s = Sort[r, #1[[1]] < #2[[1]] &]; 

(* find min x value and corresponding y value *) 
minpair = s[[1]]; 

(* ditto for max x value *) 
maxpair = s[[-1]]; 

(* return the pure function representing cutoff interpolation *) 
Piecewise[{ 
{minpair[[2]] &, #1 < minpair[[1]] &}, 
{maxpair[[2]] &, #1 > maxpair[[1]] &}, 
{Interpolation[r], True} 
}]] 

test = Table[{x,Prime[x]},{x,1,10}] 

InputForm[interpcut[test]] 

Piecewise[{{minpair$59[[2]] & , #1 < minpair$59[[1]] & }, 
    {maxpair$59[[2]] & , #1 > maxpair$59[[1]] & }}, 
InterpolatingFunction[{{1, 10}}, {3, 1, 0, {10}, {4}, 0, 0, 0, 0}, 
    {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}, {{2}, {3}, {5}, {7}, {11}, {13}, {17}, 
    {19}, {23}, {29}}, {Automatic}]] 

我敢肯定我錯過了一些基本的東西。什麼?

回答

4

函數定義

interpcut[r_, x_] := 
    Module[{s},(*sort array by x coord*) 
     s = SortBy[r, First]; 
     Piecewise[ 
     {{First[s][[2]], x < First[s][[1]]}, 
     {Last [s][[2]], x > Last [s][[1]]}, 
     {Interpolation[r][x], True}}]]; 

測試

test = Table[{x, Prime[x]}, {x, 1, 10}]; 
f[x_] := interpcut[test, x] 
Plot[f[x], {x, -10, 30}] 

alt text

編輯

回答您的評論對純函數。

我這樣做只是爲了清晰,不是爲了作弊。對於使用純函數只是「按照食譜」:

interpcut[r_] := Module[{s}, 
    s = SortBy[r, First]; 
    Function[Piecewise[ 
    {{First[s][[2]], # < First[s][[1]]}, 
    {Last [s][[2]], # > Last [s][[1]]}, 
    {Interpolation[r][#], True}}]] 
    ] 

test = Table[{x, Prime[x]}, {x, 1, 10}]; 
f = interpcut[test] // InputForm 
Plot[interpcut[test][x], {x, -10, 30}] 
+0

OK,但是這欺騙。我希望它能像Interpolation []那樣返回一個純函數。 interpcut應該將一個數組作爲輸入並返回一個純函數作爲輸出。否則,我不得不重寫很多東西。 – barrycarter 2010-12-18 03:56:21

+0

好吧,事實證明,調用你的函數interpcut1,然後做: interpcut [r_]:=函數[x,interpcut1 [r,x]] 有竅門。 – barrycarter 2010-12-18 04:49:14

+0

@barrycarter是的,一旦你得到了純粹的功能,你可以重新定義它,只要你想...... – 2010-12-18 04:52:44

2

這裏是一個可能的替代貝利薩留的回答是:

interpcut[r_] := Module[{s}, s = SortBy[r, First]; 
    Composition[Interpolation[r], Clip[#, Map[First, Through[{First, Last}[s]]]] &]] 
+2

編碼高爾夫岩石! 「interpcut [r_]:= 組合[Interpolation [r],Clip [#,Map [First,Through [{First,Last} [SortBy [r,First]]]]]&]」(look ma,no module !) – barrycarter 2010-12-28 18:27:48

+0

@barry:代碼高爾夫確實是一個很好的遊戲* Mathematica * ... :) – 2010-12-29 00:43:04

+2

@barrycarter我們可以做得更好一點:'interpcut [r _]:= Interpolation [r] [#〜剪輯〜SortBy [DAT,首先] [[{1,-1},1]]]&' – 2011-11-25 15:56:27

1

讓我的更新添加到這個古老的線程。由於V9可以使用原生的(但仍處於試驗階段) 「ExtrapolationHandler」 參數

test = Table[{x, Prime[x]}, {x, 1, 10}]; 

g = Interpolation[test, "ExtrapolationHandler" -> 
     {If[# <= test[[1, 1]], test[[1, 2]], test[[-1, 2]]] &, 
     "WarningMessage" -> False}]; 

Plot[g[x], {x, -10, 30}] 

enter image description here