フィルターのクリア

What is the error here? Euler Method for 2nd order equations?

1 回表示 (過去 30 日間)
Kaylene Widdoes
Kaylene Widdoes 2016 年 2 月 17 日
コメント済み: Torsten 2016 年 2 月 18 日
I have the following files and script file, but the graph is definitely wrong for the approximations. Any ideas?
Code:
clear all
% define the problem: function f and domain
f = @(t,y) (0*t+3*y);
a = 0; b = 1;
% exact solution, using a fine grid
t = a:.0001:b;
y = exp(3*t); % this is a vector of values, not a function
% coarse solution
h = .25;
ya = 1;
[T1,Y1]=euler(f,a,b,ya,h);
% fine solution
h = .05;
ya = 1;
[T2,Y2]=euler(f,a,b,ya,h);
% finer solution
h = .01;
ya = 1;
[T3,Y3]=euler(f,a,b,ya,h);
plot(t,y,'k',T1,Y1,'bo-',T2,Y2,'ro-',T3,Y3,'go-')
legend('Exact','h=0.25','h=0.05','h=0.01')
title('The Euler Method with 3 meshes')
Script File:
function[T,Y] = euler(f,a,b,ya,h)
a = 0; b = 1;
T = a:h:b;
Y = zeros(1,length(T));
Y(1) = a;
for k = 1 : length(T)-1
Y(k+1) = Y(k) + h*f(T(k),Y(k));
end
  1 件のコメント
Walter Roberson
Walter Roberson 2016 年 2 月 17 日
Are you encountering an error message? What do you observe that leads you to be suspicious of the code?

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

採用された回答

Torsten
Torsten 2016 年 2 月 17 日
function[T,Y] = euler(f,a,b,ya,h)
a = 0; b = 1;
T = a:h:b;
Y = zeros(1,length(T));
*Y(1) = ya;*
for k = 1 : length(T)-1
Y(k+1) = Y(k) + h*f(T(k),Y(k));
end
Best wishes
Torsten.
  2 件のコメント
Kaylene Widdoes
Kaylene Widdoes 2016 年 2 月 17 日
So if I want to run the same code for (x^3)y' + 20(x^2)y = x, would I solve for dy/dx and then plug that equation in?
Torsten
Torsten 2016 年 2 月 18 日
Yes.
f = @(t,y) (t-20*t^2*y)/t^3;
Best wishes
Torsten.

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by