Forward Euler solution plotting

32 Ansichten (letzte 30 Tage)
Michael Swanson
Michael Swanson am 12 Jan. 2019
Bearbeitet: Torsten am 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)

Antworten (1)

Torsten
Torsten am 14 Jan. 2019
Bearbeitet: Torsten am 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

Kategorien

Mehr zu Numerical Integration and Differential Equations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by