3
$\begingroup$

I'm trying to create a dynamic piecewise function. I can get 3 points, but after that, everything gets a bit complicated:

Manipulate[DynamicModule[{pts =  {{0, 0}, {1, 1}, {2, 2}}},
    LocatorPane[Dynamic[pts],
        Dynamic[Column[{Plot[
            Piecewise[{
                {x (y2 - y1)/( pts[[2, 1]] - pts[[1, 1]]), 
                pts[[1, 1]] <= x < pts[[2, 1]]},
                {x (y3 - y2)/(pts[[3, 1]] - pts[[2, 1]]) + (y2 - y1)/( 
                pts[[2, 1]] - pts[[1, 1]]) - (y3 - y2)/(pts[[3, 1]] - 
                pts[[2, 1]]), pts[[2, 1]] <= x < pts[[3, 1]]}
           }],
        {x, 0, 2}, PlotRange -> {{0, 2}, {0, 2}}, ImageSize -> Large],
            Piecewise[{{x (y2 - y1)/(pts[[2, 1]] - pts[[1, 1]]),   pts[[1, 1]] <= x < 
            pts[[2, 1]]}, {x (y3 - y2)/(pts[[3, 1]] - pts[[2, 1]]) 
            + (y2 - y1)/(pts[[2, 1]] - pts[[1, 1]]) - (y3 - y2)/(pts[[3, 1]] 
            - pts[[2, 1]]), pts[[2, 1]] <= x < pts[[3, 1]]}}]}]],       
        Appearance -> None]],
{y1, 0, 2}, {{y2, 1}, 0, 2, Appearance -> None}, {{y3, 2}, 0, 2}]

enter image description here

Is there a nice way to do this?

$\endgroup$

1 Answer 1

4
$\begingroup$
ClearAll[toPW]
toPW[pts_, x_] := Piecewise[{#[[2]] + (#2/# & @@ Subtract@##) (x - #[[1]]), #[[1]] <= 
      x <= #2[[1]]} & @@@ Partition[SortBy[First]@pts, 2, 1]]

DynamicModule[{pts = {{0, 0}, {1, 1}, {2, 0}, {3, 2}}}, 
 LocatorPane[Dynamic[pts], 
  Dynamic[Plot[toPW[pts, x], {x, 0, 3}, PlotRange -> 3, 
    Exclusions -> None, Frame -> True, Axes -> False,
    PlotLabel -> toPW[pts, x]]], 
  LocatorAutoCreate -> True]]

enter image description here

Manipulate[Plot[toPW[pts, x], {x, 0, 3}, PlotRange -> 3, Exclusions -> None, 
    Frame -> True, Axes -> False,  PlotLabel -> toPW[pts, x]], 
 {{pts, {{0, 0}, {1, 1}, {2, 0}, {3, 2}}}, Locator, LocatorAutoCreate -> True}]

enter image description here

$\endgroup$
1
  • $\begingroup$ amazing - thank you $\endgroup$ Commented Mar 20, 2021 at 7:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.