# Piecewise function with form determined by current value

I would like to create a piecewise function that determines the dynamics of a variable $$x_t$$ as follows:

Given a starting value $$x_0$$ and a parameter $$\hat{x}$$:

xHat = 0.10;
x0 = 0.15;


Let $$x_t$$ evolve according to $$x_t=e^{-1.5 t} x_0$$ if $$x_t$$ is above $$\hat{x}$$, according to $$x_t=e^{-1.2 t} x_0 + 0.0027(1 - e^{-1.2 t})$$ once $$x_t$$ goes below $$\hat{x}$$ and in general switch between the two evolutions based on the current value of $$x_t$$. I have set it up as follows:

xP[t_] := E^(-1.5*t)*x0
xN[t_] := E^(-1.2*t)*x0 + 0.0027*(1 - E^(-1.2*t))
myfun = Piecewise[{{xP[t], xP[t] > xHat}, {xN[t], xN[t] < xHat}}]
Plot[{xP[t], xN[t], myfun}, {t, 0, 1}, PlotRange -> All]


But this does not work. Here is the plot:

Instead I would expect the line to start on the blue trajectory, and then jump to the yellow one when the function goes below 0.1.

How should I correctly define the piecewise function?

• Read the error message. I don't know if this is the entirety of your problem, but the first step would be making this change: Piecewise[{{xP[t], xP[t] > xHat}, {xN[t], xN[t] < xHat}}]. Dec 15, 2022 at 16:58
• Thanks, it was an error because I didn't copy and paste the code, but it was not the problem Dec 15, 2022 at 17:01

It is not clear what you want. Your piecewise function does not define a function value for x approx. between 0.27 and 0.34. Therefore myfun uses the default value of zero.

If you want that myfun switches from xP[t] to xN[t] if xP[t]<xHat, you must write:

myfun[t_] = Piecewise[{{xP[t], xP[t] > xHat}, {xN[t], xP[t] < xHat}}];
Plot[{xP[t], xN[t], myfun[t]}, {t, 0, 1}, PlotRange -> All]