Azzera filtri
Azzera filtri

Error using ode45

1 visualizzazione (ultimi 30 giorni)
Javier Negron
Javier Negron il 7 Mag 2021
Commentato: Jan il 8 Mag 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 Commento
James Tursa
James Tursa il 7 Mag 2021
Modificato: James Tursa il 7 Mag 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);

Accedi per commentare.

Risposta accettata

Jan
Jan il 7 Mag 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 Commenti
Javier Negron
Javier Negron il 7 Mag 2021
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 il 8 Mag 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:

Accedi per commentare.

Più risposte (0)

Tag

Prodotti


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by