Forward Euler solution plotting

조회 수: 19 (최근 30일)
Michael Swanson
Michael Swanson 2019년 1월 12일
편집: Torsten 2019년 1월 14일
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)

답변 (1개)

Torsten
Torsten 2019년 1월 14일
편집: Torsten 2019년 1월 14일
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

카테고리

Help CenterFile Exchange에서 Numerical Integration and Differential Equations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by