Where is the mistake in this Euler Method code?

Using the following Euler Method function code:
function [y,t] = ODE_euler(F,y0,a,b,n)
t = linspace(a,b,n)';
h = t(2)-t(1);
y = zeros(n,1);
y(1) = y0;
for i=2:n
y(i) = y(i-1) + h*feval(F,t(i-1),y(i-1));
end
f1 = inline('1/(t.^2)','t','y');
[y,t] = ODE_euler(f1,0,1,3,11);
ye = (-1/t)+1;
norm(y-ye,inf)
plot(t,y)
hold on
plot(t,ye,'r')
For y' = t^(-2), y(1)=0, t in [1,3] using exact solution: y = -t^(-1)+1, but am getting 10.6667 as an answer and the corresponding plot is clearly wrong? I'm a novice MATLAB user and can't tell if it's b/c of a misuse of the function or code syntax.

 Réponse acceptée

Use ./ instead of / for division.
I recommend you use anonymous functions instead of inline().
f1 = @(t, y) 1./(t.^2);

Plus de réponses (0)

Catégories

En savoir plus sur General Applications dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by