MATLAB: ODE function does not seem to work

codeodeode45

Want to run this script to solve the function but it doesn't seem to work no matter if i use ode45 or ode23
t0=0;tf=20;
x0=[0;0.25];
[t,x]= ode45('sdof',[t0 tf],0);
plot(t,x)
function xdot = sdof(t,x)
k=3; c=1 m=3;
A=[0 1;-k/m -c/m];
xdot=A*x;
function xdot = sdof(t,x)
Error: Function definitions are not permitted in this context.
Error using feval
Undefined function 'sdof' for input arguments of type 'double'.
Error in odearguments (line 90)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);

Best Answer

You need to make a few adjustments in your code.
This:
k=3; c=1; m=3;
sdof = @(t,x) [0 1;-k/m -c/m]*x(:);
t0=0;
tf=20;
x0=[0;0.25];
[t,x]= ode45(sdof,[t0 tf],x0);
plot(t,x)
grid
works for me, and produces this plot:
ODE function does not seem to work - 2018 11 16.png
Related Question