MATLAB: Error in ode45 (Index exceeds matrix dimensions)

function inside ode

Can someone please explain what I have to fix for the AF_function_in(t) of my code?
My function is as followed:
function dx=myeqn(t,x,p)
global tu;
function output=AF_function_in(t)
output=interp1(tu(:,1),tu(:,2),t);
end
dx(1,1)= (p(1)/p(2))*(AF_function_in(t)-x(1))- (p(4)/p(2))*(x(1)-x(2));
dx(2,1)= (p(4)/p(3)) *(x(1)-x(2));
end
When I run:
tv=1x225 matrix;
[t,x]=ode45(@(t,x) myeqn (t,x,[0.1 0.2 0.3 0.4],tv,[0 0]));
I get an error of:
Error in myeqn/AF_function_in (line 4)
output=interp1(tu(:,1),tu(:,2),t);
Error in myeqn (line 6)
dx(1,1)= (p(1)/p(2))*(AF_function_in(t)-x(1))- (p(4)/p(2))*(x(1)-x(2));
Error in @(t,x)myeqn(t,x,[0.1,0.2,0.3,0.4])

Best Answer

First, ‘tu’ has to be an (Nx2) matrix.
Second, do not use global variables! They make your code much more difficult to troubleshoot. Pass ‘p’ and ‘tu’ as extra parameters instead.
Try this:
function dx=myeqn(t,x,p,tu)
output=interp1(tu(:,1),tu(:,2),t);
dx(1,1)= (p(1)/p(2))*(AF_function_in(t)-x(1))- (p(4)/p(2))*(x(1)-x(2));
dx(2,1)= (p(4)/p(3)) *(x(1)-x(2));
end
and then call it in your ODE solver as:
[t,x] = ode45(@(t,x) myeqn(t,x,p,tu), tspan, x0);
with ‘x0’ being your (2x1) initial conditions vector.