MATLAB: Using interp1 on ode45

interp ode45interp1interpolationode45

i try to implement interpolation on ode45 but mostly error pop up, plus i dont really understand how it works. these are codes used…
function dxdt = forced(t,x)
dxdt_1 = x(2);
dxdt_2 = -100*x(2)-250000*x(1)+ sin(500*t);
dxdt = [dxdt_1;dxdt_2];
tspan=[0:0.1:100];
initial_x=0;
initial_dxdt=0;
[t,x]=ode45(@forced,tspan,[initial_x initial_dxdt]);
figure
plot(t,x(:,1));
grid on
this will result to having x data..
now, i want to interpolate x data into f(see below function)…
function dxdt = forced(t,x)
dxdt_1 = x(2);
dxdt_2 = -100*x(2)-250000*x(1)+(25000*(f(t)^3));
dxdt = [dxdt_1;dxdt_2];
tspan=[0:0.1:100];
initial_x=0;
initial_dxdt=0;
f=interp1(x1,p,x);
[t1,x1,f]=ode45(@forced,tspan,[initial_x initial_dxdt]);
but it doesnt work, and error pops such as Index exceeds matrix dimensions.
Error in interp1>sortxv (line 423)
V = V(idx,:);
Error in interp1 (line 186)
[X, V] = sortxv(X,V);
...
any body has any suggestion or correct my codes, thanks.

Best Answer

  • The problem as I see it is that you haven’t defined ‘x1’, ‘p’, or ‘x’ before this line:
    f=interp1(x1,p,x);
    at least in the code you posted. Also, this line:
    [t1,x1,f]=ode45(@forced,tspan,[initial_x initial_dxdt]);
    will likely throw an error.
    I would not interpolate the output of ode45, instead I would simply define a ‘tspan’ vector with the points I wanted the ODE to be evaluated.