How to define piecewise function of multiple variables?

9 views (last 30 days)
I need to create a piecewise function in Matlab where I have a differential equation I'm trying to use ode45 on where dfdt=@(t,x) (A/B)*E + (E/A) - (A/C)*x - x*B; A,B, and C are all known constants. The function inputs for dfdt are t and x, and I need the t there too because I'm going to use ode45. Here's where it gets weird, E is a constant too but it's value changes depending on what t is. If 35<t<246 then E is 7. Otherwise, E is 1. Any help?

Answers (1)

Walter Roberson
Walter Roberson on 17 Apr 2018
You cannot use piecewise functions with any of the ode* routines. The ode* routines expect that the function is continuous and will complain if the derivative of any of the computed values has a singularity.
You need to run ode45 multiple times, once for each time span that has a continuous E. Take last time's output values as the input values for the next ode call.
  2 Comments
Hunter Weaver
Hunter Weaver on 18 Apr 2018
Thanks for your help, but what do you mean by taking last time's output values as the input values for the next ode call? In my case, I would run ode45 3 times right?
Walter Roberson
Walter Roberson on 18 Apr 2018
E = [1, 7, 1];
x0 = ...
[t1, x1] = ode45(@(t,x) @(t,x) (A/B)*E(1) + (E/A) - (A/C)*x - x*B, [0 35], x0);
[t2, x2] = ode45(@(t,x) @(t,x) (A/B)*E(2) + (E/A) - (A/C)*x - x*B, 35 246], x1(end,:));
[t3, x3] = ode45(@(t,x) @(t,x) (A/B)*E(3) + (E/A) - (A/C)*x - x*B, [246 ENDPOINT], x3(end,:));
t = [t1; t2(2:end); t3(2:end)];
x = [x1; x2(2:end,:); x3(2:end,:)];
The 2:end in calculating the final variable is to avoid having two copies of the output at the boundary times.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!