# When event and “stop integration”

I am using NDSolve, to solve for an equation. At some point, I want it to stop integrating and keep a constant value for the solution from the point it stopped changing. I tried setting the derivative of the solution to 0 (using whenevent), but it won't let me. So I tried using "stop integration" in the "when event", which basically makes the curve diverge. UNLESS I set the value of a function to the function itself (f[x]->f[x]) which for some reason makes IT STAY constant. But, from that point on, none of the conditions I set for whenevent are ever met again (I would like that the integration continues after uf[t]>uc[t]. Can someone explain to me what is going on? How could I resolve this problem?, Is there a better way to do that?

uf[t_] := U/\[Pi] + U/2 Sin[t] - (2*U)/\[Pi] Sum[1/((2 n - 1) (2 n + 1))*Cos[2 n*t],{n, 50}];

a = Last[
NDSolve[{uf[t] == R c uc'[t] + uc[t], uc[0] == 0,
WhenEvent[uf[t] - uc[t] < 0 && t != 0, {"StopIntegration", uc[t] -> uc[t]}],
WhenEvent[uf[t] - uc[t] > 0, "RestartIntegration"]}, uc, {t, 0, 10}]
//. Rule -> List // Flatten];

-

You need to specify numeric values for the parameters U, R, c (normally one avoids starting names with capital letters in Mathematica). Since you did not, I made them up.

As for the principal problem, one approach is to use the DiscreteVariables option to switch between your differential equation and the equation uc'[t] == 0.

U = R = c = 1;

uf[t_] := U/π + U/2 Sin[t] - (2*U)/π Sum[1/((2 n - 1) (2 n + 1))*Cos[2 n*t], {n, 50}];

a = NDSolveValue[{R c uc'[t] == on[t] (uf[t] - uc[t]), uc[0] == 0, on[0] == 1,
WhenEvent[uf[t] - uc[t] < 0 && t != 0, on[t] -> 0],
WhenEvent[uf[t] - uc[t] > 0, on[t] -> 1]}, uc, {t, 0, 10},
DiscreteVariables -> {on[t] ∈ {0, 1}}
];

Plot[a[t], {t, 0, 10}]


(I wonder what happened to the t axis.)

The explanation of what happens in the OP's code is that when the event "StopIntegration" occurs, NDSolve stops integration -- that is, it quits. Subsequent events are not reached. (To verify, examine the domain of the returned InterpolatingFunction.)

-