ODE function does not seem to work

7 views (last 30 days)
Pooh
Pooh on 16 Nov 2018
Commented: Pooh on 16 Nov 2018
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);

Accepted Answer

Star Strider
Star Strider on 16 Nov 2018
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

More Answers (2)

Aquatris
Aquatris on 16 Nov 2018
First error is in sdof function. There should be a semicolon after c=1 and before m=3;
k=3; c=1; m=3;
Second error is in your function call to ode45. Your x is a 2x1 vector however you define initial condition with a 1x1 vector. You forgot to call it with x0.
After fixing these two things, the code ran fine in Matlab 2017a. Below are the code I ran;
function xdot = sdof(t,x)
k=3; c=1; m=3;
A=[0 1;-k/m -c/m];
xdot=A*x;
Script;
t0=0;tf=20;
x0=[0;0.25];
[t,x]= ode45('sdof',[t0 tf],x0);
plot(t,x)
  1 Comment
Pooh
Pooh on 16 Nov 2018
This error shows up when running the code you mentioned in R2018a
Not enough input arguments.
Error in sdof (line 4)
xdot=A*x

Sign in to comment.


Steven Lord
Steven Lord on 16 Nov 2018
Which release of MATLAB are you using? The ability to define local functions in script files was introduced in release R2016b. For earlier releases you'll need to main the first part of your code into a function, in which case sdof will be a local function in a function file, or you'll need to move sdof into its own file sdof.m.
You should also specify the first input argument to ode45 as a function handle rather than the name of a function. While specifying the name is supported for backwards compatibility, we stopped documenting that syntax at least 10 to 15 years ago and newer (relatively speaking) functions that accept functions as input likely won't accept the name of a function specified as a string or a char array. [For example, the integral function introduced in release R2012a does not.]
  1 Comment
Pooh
Pooh on 16 Nov 2018
I am currently using R2016b; I have also tried using the @ function handle but the code is still not working. Hope that you would be able to provide me advice on this.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!