How do I solve this differential equation?

11 ビュー (過去 30 日間)
Patrick Brandt
Patrick Brandt 2024 年 10 月 17 日
コメント済み: John D'Errico 2024 年 10 月 17 日
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!

採用された回答

Sam Chak
Sam Chak 2024 年 10 月 17 日
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 件のコメント
John D'Errico
John D'Errico 2024 年 10 月 17 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOrdinary Differential Equations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by