Time differing coefficient ODE

Hi everyone,

I am wanting to solve the differential equation

dx/dt=-x+y; dy/dt=-t*y+3x
x(0)=0; y(0)=1; t(0)=0; note t is a time varying coefficient

I tried the subsequent code but I didn’t think it calculate it correctly or maybe it’s correct but I’m unware??? My question is if there is a way to account for the time dependent parameter in the ODE? Thanks a lot.

   using DifferentialEquations
   using Plots

   # Define the differential equations
   function system!(du, u, p, t)
       x, y = u
       dxdt = -x + y
       dydt = -t*y + 3*x
       du[1] = dxdt
       du[2] = dydt
   end

   # Initial conditions
   u0 = [0.0, 1.0]  # [x(0), y(0)]

   # Time span
   tspan = (0.0, 1.0)

   # Create an ODE problem
   prob = ODEProblem(system!, u0, tspan)

   # Solve the ODE problem
   sol = solve(prob)

   # Print the solution
   println(sol)

   plot(sol, title="Solution of the differential equations",
        xlabel="t", ylabel="Values", label=["x(t)" "y(t)"])

What do you think is incorrect?

1 Like

I don’t know the details, but I think you can try using ModelingToolkit.jl. Based on your requirements and the docs, I think the following code should meet your requirements:

beginbegin
	# for modeling
	using ModelingToolkit
	using ModelingToolkit: t_nounits as t, D_nounits as D
	# for solve
	using DifferentialEquations
	# for plot
	using CairoMakie

	# define model
	@mtkmodel TimeModel begin
		# variables and initial values
		@variables begin
			x(t) = 0.0
			y(t) = 1.0
		end
		# equations
		@equations begin
			# dx/dt = -x + y
			D(x) ~ -x + y
			# dy/dt = -t * y + 3x
			D(y) ~ -t * y + 3x
		end
	end

	# build model
	@mtkbuild timemodel = TimeModel()

	# solve for t ∈ [0.0, 1.0]
	odeproblem = ODEProblem(timemodel, [], (0.0, 1.0), [])
	solution = solve(odeproblem)

	# extract values
	t_table = solution.t
	x_table = [solution.u[i][1] for i = 1:length(solution.u)]
	y_table = [solution.u[i][2] for i = 1:length(solution.u)]

	# plot solution
	solution_figure = Figure()
	solution_axis = Axis(solution_figure[1, 1];
		aspect = 1.0,
		xticks = 0.0:0.2:1.0,
		yticks = 0.0:0.2:1.6,
		title = "Solution of the differential equations",
		titlesize = 16)
	lines!(solution_axis, t_table, x_table; label = L"x\,{(t\,)}")
	lines!(solution_axis, t_table, y_table; label = L"y\,{(t\,)}")
	axislegend(solution_axis; position = :rb)
	save("ode_solution.png", solution_figure)
	solution_figure
end

The plot is:

Because I don’t understand this model, I don’t know if this is the result you want.

2 Likes

I was wrong by misunderstanding the model. So there is nothing wrong with the ODE solutions. Sorry for the trouble.