Implementing forward Euler method

3 ビュー (過去 30 日間)
Matthew Kaplan
Matthew Kaplan 2017 年 11 月 13 日
コメント済み: Torsten 2017 年 11 月 13 日
So I'm working on part(b) and I'm unsure how to plot the error versus step size on a log-log scale. Here is the code I have thus far...
function [tgrid, Y] = euler_method(fun, y_0, n, T)
if nargin(fun) ~=2
error('fun must take two inputs, t and y.');
end
if ~all(size(y_0) == size(fun(0, y_0)))
error('You have not passed appropriate fun or y_0.');
end
%Set up the time grid. ***NOTE THE n+1***
tgrid = linspace(0, T, n+1);
%Compute h from the time grid.
h = tgrid(2) - tgrid(1);
%Orient tgrid as a column vector.
tgrid = reshape(tgrid, n+1, 1);
%How many equations?
m = length(y_0);
%Orient y0 as a row vector.
y_0 = reshape(y_0, 1, m);
% Preallocate an array to hold the approximate solution. Each row
% corresponds to a point in the time grid.
Y = zeros(n+1, m);
% Set the initial conditions.
Y(1,:) = y_0;
% Euler loop
for i = 1: n
% Store the point in time as a temporary variable
t_i = tgrid(i);
% Take the Euler step into the temporary variable
y_1 = y_0 + h * fun(t_i, y_0);
% Store the Euler step
Y(i+1,:) = y_1;
% Update the temporary variable
y_0 = y_1;
end

採用された回答

Torsten
Torsten 2017 年 11 月 13 日
Call "euler_method" in a loop for n = 8*2^k (k=1,...,15) and store Y(n+1,1) for each run.
Then make the plot.
Best wishes
Torsten.
  4 件のコメント
Matthew Kaplan
Matthew Kaplan 2017 年 11 月 13 日
Am I on the right path at all?
Torsten
Torsten 2017 年 11 月 13 日
y_0 = 0;
tend = 8.0;
fun=@(t,y) sin(t)-y;
for k = 1:15
n = 8*2^k;
[T Y] = euler_method(fun, y_0, n, tend);
Yend(k) = Y(n+1,1);
end
Now add the plot.
Best wishes
Torsten.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by