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?
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:In your specific case, though, the piecewise function is simple enough that you can do it like this:
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 keepfin a separate file calledf.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, andfcan only be called from withinmyode.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.