MATLAB Answers

Error using ode45

3 views (last 30 days)
Javier Negron
Javier Negron on 7 May 2021
Commented: Jan on 8 May 2021
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 Comment
James Tursa
James Tursa on 7 May 2021
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);

Sign in to comment.

Accepted Answer

Jan
Jan on 7 May 2021
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 Comments
Jan
Jan on 8 May 2021
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:

Sign in to comment.

More Answers (0)

Tags

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by