MATLAB: Using ode45 for solution curve

ode45

Equations:
df/dt= 4f(t) – 3f(t)p(t)
dp/dt= -2p(t) + f(t)p(t)
Question: For the solution curve that starts at (1,1), how many units of time does it take before the curve returns to (1,1)? Try to get it within two decimal places. Repeat for the curve that starts at (0.5,0.5).
Here is the code that creates the solution curve:
gh = @(t,x) [4*x(1) - 3*x(1).*x(2); -2*x(2) + x(1).*x(2)];
tspan = linspace(0, 5, 250);
figure; hold on
for c = 0:0.1:5
[t,x] = ode45(gh, tspan, [c; c]);
plot(x(:,1), x(:,2))
end
axis tight
I was told there is a way to use ode45 to find how many units of time, but I am not sure how?

Best Answer

These are getting more challenging (and interesting).
One way is to use an 'Event' function. (You can either create a separate function file (without input arguments) and put all of these in it and then run the function from the Command Window, or save ‘EventFcn’ to a separate .m file (as ‘EventFcn.m’ and run the ODE integration from its own script file.)
The code:
function [value,isterminal,direction] = EventFcn(t,x)
value = [(x(1) - 1); (x(2) - 1)];
isterminal = [0; 0];
direction = [0; 0];
end
gh = @(t,x) [4*x(1) - 3*x(1).*x(2); -2*x(2) + x(1).*x(2)];
tspan = linspace(0, 5, 250);
c = 1;
opts = odeset('Events', @EventFcn);
[t,x,EventTime,EventXVal,ie] = ode45(gh, tspan, [c; c], opts);
% EventTime % Show Values (Delete)
% EventXVal % Show Values (Delete)
x_1_1 = abs(diff(EventXVal,1,2)) < 1.1; % Logical Vector Of Approximately Equal ‘x’ Values
EqualTimes = EventTime(x_1_1) % Corresponding Event Times
UniqueTimes = diff([0; EqualTimes]) >= 0.2 % Use ‘diff’ To Select Unique Times
ReturnTimes = EqualTimes(UniqueTimes) % Desired Result
When I run it, I get:
ReturnTimes =
1.7980
2.2888
4.0924
4.5863
Set ‘c = 0.5;’ for the second run to complete the exercise.