0
$\begingroup$

I am trying to plot the phase portrait of these three differential equations, but the problem is $z$ is a piecewise function and I don't know how to define it in my f. Let say my $z$ is expressed as below

$$ z = \begin{cases} x(1) & \text{ for } t<-1 \\ x(1)+1 & \text{ for } -1 \leq t \leq 0 \\ x(1)+2 & \text{ for } t>0 \end{cases}$$

Here is the MATLAB code,

f = @(t,x) [x(1)+x(2)+z;x(1)+x(2)+x(3); x(3)];
[t,xa] = ode45(f,[0 500],[1 0 -1]);
plot3(xa(:,1),xa(:,2),xa(:,3))
grid on

Can anyone suggest me how to include the piecewise functions in my f?

  • 0
    I don't recommend inserting discontinuities into your integration function. ODEs and ODE solvers assume a degree of continuity. You may get imprecise or even wrong answers depending on your system and how you call the solver. You should instead integrate the system piecewise and append the resultant outputs from each run. See my answers on StackOverflow [here](http://stackoverflow.com/a/21501376/2278029) and [here](http://stackoverflow.com/a/17370733/2278029).2017-02-06

1 Answers 1

0

The body of a MATLAB anonymous function is a single expression. MATLAB doesn't have a convenient if-then-else operator like C's question mark. Conclusion: in general, you are better off writing a regular function for f, where you can simply use conditionals. Something like this:

function myode
  [t,xa] = ode45(@f,[0 500],[1 0 -1]);
  plot3(xa(:,1),xa(:,2),xa(:,3))
  grid on
end

function ydot = f(t,x)
  if t < -1
    z = x(1);
  elseif t <= 0
    z = x(1) + 1;
  else
    z = x(1) + 2;
  end
  ydot = [x(1)+x(2)+z; x(1)+x(2)+x(3); x(3)];
end

In your specific case, though, the piecewise function is simple enough that you can do it like this:

f = @(t,x) [2*x(1)+x(2)+(t >= -1)+(t > 0); x(1)+x(2)+x(3); x(3)];

This solution exploits the fact that MATLAB coerces logical values to numbers in an arithmetic expression.

The "regular" function approach gives you the most flexibility in describing your ODEs, but MATLAB requires that functions be stored in function files. So the first code sample needs to be saved in a file named myode.m. (You could keep f in a separate file called f.m, but I'd go with one file for both functions. If you do so, the name of the file must be the name of the first function, and f can only be called from within myode.m.)

Anonymous functions, on the other hand, may appear anywhere in MATLAB code. In particular, they may appear in scripts and on the command line.

  • 0
    Thanks for replying. Anyway, I am still confused. How to include that function file in the ode45 command. Can you please show me the full code? Sorry, I am a bit new to this ode solver.2017-02-06
  • 0
    @Peter Check if the additions I just made answer your question.2017-02-06
  • 0
    Thanks a lot guys. The code works well now.2017-02-07