How do I solve this differential equation?

1 Ansicht (letzte 30 Tage)
Patrick Brandt
Patrick Brandt am 17 Okt. 2024
Kommentiert: John D'Errico am 17 Okt. 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!

Akzeptierte Antwort

Sam Chak
Sam Chak am 17 Okt. 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 Kommentar
John D'Errico
John D'Errico am 17 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by