Forward Euler solution plotting

20 vues (au cours des 30 derniers jours)
Michael Swanson
Michael Swanson le 12 Jan 2019
Modifié(e) : Torsten le 14 Jan 2019
Hi,
I am trying to solve the differential equation dx/dy=x-y from x=0 to 1.5 using the forward euler method with step sizes 0.25, 0.05, and 0.01. I want to plot the approximations of all three step sizes on one plot, with the exact solution y=(x+1)-(1/3)e^x as well. I have the first approximation and plot with step size 0.25 in the code below. I was thinking I would use an array of step sizes where h=[0.25 0.05 0.01] and N=[6 30 150] but it's not working. How should I go about this?
h=0.25; % step size
N=6; % number of steps
y(1)=2/3; % Initial condition
for n=1:N
x(n+1)=n*h
y(n+1)= y(n)+h*(y(n)-x(n)) % FWD Euler solved for y(n+1)
end
plot(x,y)

Réponses (1)

Torsten
Torsten le 14 Jan 2019
Modifié(e) : Torsten le 14 Jan 2019
function main
x0 = 0.0;
x1 = 1.5;
fun = @(x,y) y-x;
h = [0.25 0.05 0.01];
for i = 1:numel(h)
[x{i},y{i}] = euler(fun,x0,x1,h(i));
end
plot(x{1},y{1},x{2},y{2},x{3},y{3})
end
function [x,y] = euler(fun,x0,x1,h)
x(1) = x0;
y(1) = 2.0/3.0;
N = (x1-x0)/h;
for i=2:N+1
y(i) = y(i-1) + h*fun(x(i-1),y(i-1));
x(i) = x(i-1) + h;
end
end

Catégories

En savoir plus sur Numerical Integration and Differential Equations dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by