How do I solve this differential equation?

2 visualizaciones (últimos 30 días)
Patrick Brandt
Patrick Brandt el 17 de Oct. de 2024
Comentada: John D'Errico el 17 de Oct. de 2024
Hi,
for a Project I have to solve the following differential equation:
y''=-((m*B0)/I)*sin(y)
m, B0 and I are numerical values
I already tried the following but it won't work.
B0=0.0354;
m=7.6563e-5;
I=1.2272e-14;
tspan=[0, 0.0001];
y0=0.139626;
[t,y] = ode45(@(t,y) odefcn(t,y), tspan, y0);
function dydt=odefcn(y,m,B0,I)
dydt=y;
dydt(1)=-(m*B0)/I*sin(y);
end
Thanks in advance!

Respuesta aceptada

Sam Chak
Sam Chak el 17 de Oct. de 2024
Put the constants inside the function.
tspan = [0, 1e-3];
y0 = [0.139626; 0];
[t, y] = ode45(@(t,y) odefcn(t,y), tspan, y0);
plot(t, y), grid on
function dydt=odefcn(t, y)
B0 = 0.0354;
m = 7.6563e-5;
I = 1.2272e-14;
dydt = zeros(2, 1);
dydt(1) = y(2);
dydt(2) = -(m*B0)/I*sin(y(1));
end
  1 comentario
John D'Errico
John D'Errico el 17 de Oct. de 2024
Or, just use a function handle. The function handle grabs whatever values of those constants from the caller workspace it needs, then stores them in the workspace of the function handle. So you need not write an m-file function, and you can pass around the function handle now, where it will always know those values.
B0 = 0.0354;
m = 7.6563e-5;
I = 1.2272e-14;
dydt = @(t,y) [y(2) ; -(m*B0)/I*sin(y(1))];
tspan = [0, 1e-3];
y0 = [0.139626; 0];
[t, y] = ode45(dydt, tspan, y0);
plot(t, y), grid on
Just be careful, as if you then later on change the values of B0. m, or I, the change will not be reflected in the function handle workspace. It will still remember the original values.
So alternatively, if you wanted to pass in those values to the function handle, you could do this:
dydt = @(t,y,B0,m,I) [y(2) ; -(m*B0)/I*sin(y(1))];
tspan = [0, 1e-3];
y0 = [0.139626; 0];
[t, y] = ode45(@(t,y) dydt(t,y,B0,m,I), tspan, y0);
plot(t, y), grid on
As you can see, the parameters B0, m, and i are all being passed into dydt, because I created a new function handle on the fly in the call to ode45. Now if you wanted to change those values later on, it is easier to do.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Ordinary Differential Equations en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by