# ODE function does not seem to work

23 ビュー (過去 30 日間)
Pooh 2018 年 11 月 16 日
コメント済み: Pooh 2018 年 11 月 16 日
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);

サインインしてコメントする。

### 採用された回答

Star Strider 2018 年 11 月 16 日
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: サインインしてコメントする。

### その他の回答 (2 件)

Aquatris 2018 年 11 月 16 日
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 件のコメント表示非表示 なし
Pooh 2018 年 11 月 16 日
This error shows up when running the code you mentioned in R2018a
Not enough input arguments.
Error in sdof (line 4)
xdot=A*x

サインインしてコメントする。

Steven Lord 2018 年 11 月 16 日
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 件のコメント表示非表示 なし
Pooh 2018 年 11 月 16 日
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.

サインインしてコメントする。

### Community Treasure Hunt

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

Start Hunting!