Let's say you have a list
data = {5, 1, 3, 8};
and you want to create a Piecewise
function creator. First, you need to think about how to construct each of the linear functions. E.g. from x=1
to x=2
we need a linear function going from 5 down to 1. From x=2
to x=3
we need a function going from 1 up to 3 and so on. This is simple math, but you can also use Mathematica for this:
Rescale[x, {pos, pos + 1}, {y1, y2}] // FullSimplify
(* (1 + pos - x) y1 + (-pos + x) y2 *)
This is the expression which interpolates the x-range from pos
to pos+1
where y1
is its starting value and y2
the value at the right end. For our piecewise-creator we need to fill this expression for all adjacent pairs
{{5,1},{1,3},{3,8}}
The above structure can easily be created with the help of Partition
. The only thing that's left is a function which takes two values and inserts them into our linear function expression. Putting everything together gives our piecewise-function-creator
createPiecewise[l_List] := Piecewise[MapIndexed[
With[{pos = First[#2], y1 = First[#], y2 = Last[#]},
{y1 (1 + pos - x) + y2 (x - pos), pos <= x < pos + 1}] &,
Partition[l, 2, 1]]
]
Testing it with our data
and we get
Now you can work with it or plot it
Plot[createPiecewise[data], {x, 1, 4}]
Piecewise
. $\endgroup$