Error using ode45

6 次查看(过去 30 天)
Javier Negron
Javier Negron 2021-5-7
评论: Jan 2021-5-8
Trying to solve this functions but it give me this error.
global m g r I ks
m = 5;
g = 9.81;
r = 0.470;
I = 0.37;
ks = 0.012;
dt = 0.01;
tspan = (0:dt:5);
x0 = [0,0];
[t,x] = ode45(funcionMAT,tspan,x0);
plot(t,x(:,1));
plot(t,x(:,2));
a = x(2)-x(1)/dt;
plot(t,a);
Error
Attempt to execute SCRIPT funcionMAT as a function:
D:\Users\Javier E. Negron\Documents\Trabajos de universidad (ene-may 2021)\Capstone\funcionMAT.m
Error in Analisis_de_movimiento2 (line 13)
[t,x] = ode45(funcionMAT,tspan,x0);
  1 个评论
James Tursa
James Tursa 2021-5-7
编辑:James Tursa 2021-5-7
The beginning of your funcionMAT.m file should look like this:
function dy = funcionMAT(t,y)
And then you should use a function handle when calling ode45:
[t,x] = ode45(@funcionMAT,tspan,x0);

请先登录,再进行评论。

采纳的回答

Jan
Jan 2021-5-7
The error message means, that you need a function, because the integrator uses input and output arguments for the function to be integrated:
m = 5;
g = 9.81;
r = 0.470;
I = 0.37;
ks = 0.012;
dt = 0.01;
tspan = (0:dt:5);
x0 = [0,0];
[t,x] = ode45(@(t,y) funcionMAT(t,y, m,g,r,I,ks), tspan, x0);
% And your functionMAT file:
function dy = funcionMAT(t,y, m,g,r,I,ks)
dy = [y(1) * m + g; ... % Insert your function here
y(2)]
end
The @(t,y) functionMAT(t,y,...) method is used to provide the parameters to the function. ODE45 would call the function the inputs t and y only. This is much smarter than using global variables.
  2 个评论
Javier Negron
Javier Negron 2021-5-7
I actualy have a function file
global m g r I ks
function xdot = Analisis_de_movimiento2(~,x)
A = [0,1;(-ks*x(1)-(m*g*r/2)*cos(x(1))+(2*pi/3)*ks)*x(1)/(I + m*r^2),0];
xdot = A * [x(1);x(2)];
end
But I don't know if is not well called or some script error
Thanks in advance!
Jan
Jan 2021-5-8
If you use global variables to provide parameters, the global statement must appear in each function, which uses the global variables.
function xdot = Analisis_de_movimiento2(~,x)
global m g r I ks % Inside
A = [0, 1; ...
(-ks*x(1) - (m*g*r/2)*cos(x(1))+(2*pi/3)*ks)*x(1) / (I + m*r^2), 0];
xdot = A * [x(1);x(2)];
end
Global variables impede the debugging massively and therefore avoiding them is a good programming practice. Use an anonymous function instead as shown in my answer. See also:

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Ordinary Differential Equations 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by