Including piecewise function in ode45 - MATLAB

2.9k Views Asked by At

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?

1

There are 1 best solutions below

3
On BEST ANSWER

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.