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.