How do I solve this differential equation?

조회 수: 1 (최근 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 CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by