Mathematica [] interpolation, which remains constant over the outer range

I want to "change" the interpolation function of Mathematica [] (in 1 dimension) by replacing the extrapolation with constant values ​​when the input is out of range.

In other words, if the interpolation domain is [1,20] and f [1] == 7 and f [20] == 12, I want:

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

However, this fails:

 (* 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}]] 

I'm sure something is missing from me. What kind?

+4
source share
3 answers

Function Definition

 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

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

alt text

Edit

Responding to your comment about pure features.

I did this precisely for clarity, and not for deception. To use pure functions, simply follow the recipe:

 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}] 
+4
source

Here's a possible alternative to answering bellisaria:

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

Let me add an update for this old thread. Starting with V9, you can use your own (but still experimental) parameter "Extrapolation Handler"

 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

+1
source

Source: https://habr.com/ru/post/1332576/


All Articles