5
$\begingroup$

Suppose we have two interpolating functions with exactly touching domains, in our case {-1, 1} and {1, 2}.

How to "glue" them together without using Piecewise?

I code glue that worked very well, but there might be some functions that do the same that I do not know (maybe even undocumented).

glue[i1_, i2_] := 
 ReplacePart[
  i1, {{1, 1} -> {i1[[1, 1, 1]], i2[[1, 1, 2]]}, {2, 4} -> 
    i1[[2, 4]] + i2[[2, 4]] - 1, {3, 1} -> 
    Join[Most[i1[[3, 1]]], 
     i2[[3, 1]]], {4, 2} -> Join[#, Rest[i2[[4, 2]]] + Last[#]] &@
    Most@i1[[4, 2]], {4, 3} -> Join[i1[[4, 3, 1 ;; -3]], i2[[4, 3]]]}]


i1 = NDSolveValue[{y'[x] + y[x] == 1, y[0] == 0}, y, {x, -1, 1}]
i2 = NDSolveValue[{y'[x] + y[x] == 1, y[0] == 0}, y, {x, 1, 2}]

glue[i1, i2]

(* verifying that glued function is identical to piecewise *)
Table[glue[i1, i2][x] ===
   Piecewise[{{i1[x], -1 <= x < 1}, {i2[x], 1 <= x <= 2}}], {x, -1, 2,
    0.0001}] // Union

enter image description here

$\endgroup$
5
  • $\begingroup$ @MichaelE2 On a quick look it seems like all answers are re-interpolating joined data. My method is lossless and no re-interpolation is needed. But maybe I overlooked something, I will take a closer look tomorrow. $\endgroup$ Commented Aug 23 at 23:36
  • $\begingroup$ Ah, it's probably not what you want. $\endgroup$ Commented Aug 24 at 0:36
  • 1
    $\begingroup$ I'm pretty sure there's no built-in function. Generally, you can't combine them unless they are of the same type/sub-type. Take either ODE solution; then the following added options give IFs of different classes that cannot be combined without some sort of reconstruction: NDSolveValue[ ...]@"InterpolationMethod", NDSolveValue[..., InterpolationOrder -> All]@"InterpolationMethod", NDSolveValue[..., Method -> "ExplicitRungeKutta", InterpolationOrder -> All]@"InterpolationMethod". The first class "Hermite" has many subtypes. If i2 came from a 2nd order IVP, glue[i1, i2] would fail. $\endgroup$ Commented Aug 24 at 13:02
  • 1
    $\begingroup$ The penalty for failing to construct a proper InterpolatingFunction[] is sometimes a kernel crash, btw. -- Addendum: WhenEvent[] might cause a different sub-type to be created. If all your use-cases are exactly like your example, then glue[] should probably do the job for you. $\endgroup$ Commented Aug 24 at 13:05
  • $\begingroup$ @MichaelE2 I am using it on joining solutions of differential equation on adjacent intervals. Because sometimes you have to split intervals for NDSolveValue so that it does not fail, say, NDSolveValue fails for interval {-1, 2} but provides correct solutions for intervals {-1,1} and {1,2} so then you can join them. And this way they were always the same type. $\endgroup$ Commented Aug 24 at 13:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.