Converting Euler ODE to the MATLAB code
1 回表示 (過去 30 日間)
古いコメントを表示
Hey Everyone!
I have a question related to the Euler Method implementation. I have the following function:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/738419/image.png)
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.
0 件のコメント
採用された回答
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
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Ordinary Differential Equations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!