How can Euler's method be adapted for two-dimensional systems?

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 7K views
grimster
Messages
39
Reaction score
0
this is the classic euler's method, but i'd like to modify it so that it can handle two-dimensional systems on the form
x'=...
y'=...

what needs to be done?

function [X,Y] = euler1(x,y,x1,n)
h=(x1-x)/n;
X=x;
Y=y;
for i=1:n
y=y+h*f(x,y);
x=x+h;
X=[X;x];
Y=[Y;y];
end
X
Y
plot(X,Y,x,y)

function yp = f(x,y)
yp=y*sin(x);
 
Physics news on Phys.org
grimster said:
this is the classic euler's method, but i'd like to modify it so that it can handle two-dimensional systems on the form
x'=...
y'=...

what needs to be done?

function [X,Y] = euler1(x,y,x1,n)
h=(x1-x)/n;
X=x;
Y=y;
for i=1:n
y=y+h*f(x,y);
x=x+h;
X=[X;x];
Y=[Y;y];
end
X
Y
plot(X,Y,x,y)

function yp = f(x,y)
yp=y*sin(x);

If you want to solve a system of equations, say [y1' ; y2'] = f(x,[y1;y2]), just define y as a vector to start and make your function f return a vector [yp1;yp2].
 
grimster said:
this is the classic euler's method, but i'd like to modify it so that it can handle two-dimensional systems on the form
x'=...
y'=...

what needs to be done?

function [X,Y] = euler1(x,y,x1,n)
h=(x1-x)/n;
X=x;
Y=y;
for i=1:n
y=y+h*f(x,y);
x=x+h;
X=[X;x];
Y=[Y;y];
end
X
Y
plot(X,Y,x,y)

function yp = f(x,y)
yp=y*sin(x);

Of course, you now have 3 variables: 2 dependent and 1 independent. I would use "x" and "y" as the dependent variables, "t" as the independent variable. Just do x and y "in parallel": to solve x'= f(x,y,t), y'= g(x,y,t), xnew= xold+ hf(xold,yold,told), ynew= yold+ h*g(xold,yold,told), tnew= told+ h.