MATLAB: Solution of spring mass system with cubic stiffness

ode45spring mass system

I have below equation to solve with a given time series of gaussian white noise as f(t). Here is my code but it gives dimension error between result and the initial conditions vector. Is there any idea to fix it? Here is the error message:
Error using odearguments (line 92)
@(T,Y)SPRING(T,Y,M,C,K,K2,K3,F) returns a vector of length 10001, but the length of initial conditions vector is 2. The vector returned by @(T,Y)SPRING(T,Y,M,C,K,K2,K3,F) and the initial conditions vector must have the same number of elements.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);*
my''+cy'+ky+k2*y^2+k3*y^3=f(t)
m=1; c=1; k=10; k2=20; k3=20;
f=randn(10000,1);
tspan=[0 10000];
y0=[0;1];
function dydt=spring(t,y,m,c,k,k2,k3,f)
dydt=[y(2); (f-c*y(2)-k*y(1)-k2*y(1)^2-k3*y(1)^3)/m];
end
[t,y]=ode45(@(t,y) spring(t,y,m,c,k,k2,k3,f), tspan, y0);

Best Answer

function main
m=1; c=1; k=10; k2=20; k3=20;
tspan=[0 10000];
y0=[0;1];
f=randn(10000,1);
tf = linspace(tspan(1),tspan(end),10000); % time vector at which the f-values occured
[t,y]=ode45(@(t,y) spring(t,y,m,c,k,k2,k3,tf,f), tspan, y0)
end
function dydt=spring(t,y,m,c,k,k2,k3,tf,f)
f_actual = interp1(tf,f,t);
dydt=[y(2); (f_actual-c*y(2)-k*y(1)-k2*y(1)^2-k3*y(1)^3)/m];
end
Related Question