Converting Euler ODE to the MATLAB code

6 ビュー (過去 30 日間)
Haider Ali
Haider Ali 2021 年 9 月 14 日
コメント済み: Haider Ali 2021 年 9 月 14 日
Hey Everyone!
I have a question related to the Euler Method implementation. I have the following function:
(1)
I have written its main function code as:
function y = eulerfunction(func, t, y0)
n = length(t);
y = nan(length(y0), n);
y(:,1) = y0(:);
for k = 1:n-1
h = t(k+1) - t(k);
y(:,k+1) = y(:,k) + h*func(t(k), y(:,k));
end
end
Now I am writing the remaining script.
y0 = [3,0];
h = 0.5;
t = 0;
% I am confused in this line that what to write in these square brackets according to the given equation (1)
f = @(t, y) [ ];
y = eulerfunction(f, t, y0)
Can you please help me to convert that f(t,y) in MATLAB Format? Like what to write in these brackets '[ ]' according to the f (t,y) in above equation (1):
f = @(t, y) [ ];
Any help will be really appreciated! Thanks alot in advance.

採用された回答

Fabio Freschi
Fabio Freschi 2021 年 9 月 14 日
f is an anonymous function
f = @(t,y)[-2*y(1)+y(2)+15*cos(t); 2*y(1)-y(2)];
note that your script is not correct, since t is the time vector used for the time integration and h is calculated inside the euler function. All in all
% initial value
y0 = [3,0];
% time vector
t = linspace(0,4*pi,100);
% anonymous function
f = @(t,y)[-2*y(1)+y(2)+15*cos(t); 2*y(1)-y(2)];
% solution
y = eulerfunction(f, t, y0);
% plot
figure,plot(t,y);
% your euler method
function y = eulerfunction(func, t, y0)
n = length(t);
y = nan(length(y0), n);
y(:,1) = y0(:);
for k = 1:n-1
h = t(k+1) - t(k);
y(:,k+1) = y(:,k) + h*func(t(k), y(:,k));
end
end
  1 件のコメント
Haider Ali
Haider Ali 2021 年 9 月 14 日
thats perfect! thanks alot for this urgent help.

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

その他の回答 (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