# How to change the value of a variable at some point lying in the time interval of solver in solve_ivp

The following code solves a differential equation with scipy:

import numpy as np
from scipy.integrate import solve_ivp

t0 = 0
Z0 = np.array([0, 0, 0, 0])
sw = 0
t_final = .001
t, z = t0, Z0
if sw == 0:
sol = solve_ivp(f0, [t,t_final], z, method='BDF', events=g0)
Z = sol.y.T
t, z = sol.t[-1], Z[-1]
else:
sol = solve_ivp(f1, [t,t_final], z, method='BDF', events=g1)


where f0 and f1 are the following functions:

def f0(t, Z):
U = np.array([[vin], [vdon]])
Zdot = A*Z + B*U
return Zdot

def f1(t, Z):
U = np.array([[vin], [vdon]])
Zdot = R*Z + S*U
return Zdot


In the interval [t0,t_final] (i.e., [0,.001]), I want to change the value of vin in U = np.array([[vin], [vdon]]) at t=.0005 and onwards. To be precise, for times [.0005,.001], I want to put a different value for vin. How do I do this?

There are probably several ways to go about doing this, but one simple solution is to define f0 (and f1) so that vin depends on t. For example,

def f0(t, Z):
vin = vin_1 if t < 0.0005 else vin_2
U = np.array([[vin], [vdon]])
return A*Z + B*U


You have to define vin_1 and vin_2 elsewhere, but that should do it. In fact, vin could be a function of t, which would allow you to gradually change the value of vin throughout the integration if you wanted. Example:

vin = lambda t: t*(1 - t)

def f0(t, Z):
U = np.array([[vin(t)], [vdon]])
return A*Z + B*U