ODE function does not seem to work
7 次查看(过去 30 天)
显示 更早的评论
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);
0 个评论
采纳的回答
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:
0 个评论
更多回答(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)
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.]
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Ordinary Differential Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!