Conditionally Defining a Variable using ODE45

How could I take this code I'm using and conditionally define my variable 'p'? For example, I want p=0 everywhere except when 3<t<4, then I want p=1.2. Here is my code:
tspan=[1 7];A0=1;P0=1;g=1;p=0;B=0.15;
[t,x] = ode45(@(t,x) [-g*x(1) + p*x(1); -x(1)*x(2)+ B*x(2)], tspan, [A0 P0]);

 Respuesta aceptada

Walter Roberson
Walter Roberson el 16 de Feb. de 2019

1 voto

you need to use three ode45 calls , once for the three cases (before 3, during the range, after 4)

4 comentarios

Thomas Veith
Thomas Veith el 18 de Feb. de 2019
I really should come here first before wasting hours trying to do something that isn't possible. Thanks for your help!
Walter Roberson
Walter Roberson el 18 de Feb. de 2019
Editada: Walter Roberson el 19 de Feb. de 2019
The ode* routines expect continuity of the equations; when you have a sudden change in the value of a variable in the middle of computation, then you do not have the required continuity. The routines will complain about discontinuity if they notice; if they do not notice then they will simply give the wrong result.
Note: one of the other regular volunteers disagrees firmly with my analysis of the situation.
You could try it if you want:
P = @(t) 1.2 * (3 < t & t < 4);
[-g(x1) + P(t)*x(1) etc]
Thomas Veith
Thomas Veith el 19 de Feb. de 2019
Okay, thank you. For the method your colleague suggests, how do I fully define my variable 'p'? It seems that this code only defines for the range from 3 to 4? How do I make sure it's also defined outside the range?
Walter Roberson
Walter Roberson el 19 de Feb. de 2019
3 < t & t < 4 gives a logical result, false or true, but in most contexts those are treated as 0 and 1. So outside of 3 to 4, the test has a definite numeric value, of 0, and 0 * 1.2 is 0, so it has a well defined value of 0 outside of (3, 4) .
However, in general when you use this kind of construct, Something Times a Logical, you need to be careful in case the Something could be infinite, since infinity times 0 is nan rather than 0. Consider for example x(1) * (3 < t & t < 4) then if x(1) went to infinity there would be calculation problems outside of (3,4) . In your particular case of Something being the constant 1.2, that is not a problem, so just something to keep in mind when you start to use this construct for other purposes.

Iniciar sesión para comentar.

Más respuestas (0)

Preguntada:

el 16 de Feb. de 2019

Comentada:

el 19 de Feb. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by