0

I have two first order ODEs that I got from a second order ODE:

y(0)=1
y'(0)=-1/3

u1'=u2
u2=u/9-(pi*u1*e^(x/3)*(2u2*sin(pi*x)+pi*u1cos(pi*x))

u1(0)=y(0)=1    
u2(0)=y'(0)=-1/3

My question is how to set up forward Euler? I have that:

n=[0:0.01:2];    
h=2./n; 
horchler
  • 18,384
  • 4
  • 37
  • 73
John
  • 97
  • 2
  • 7
  • What have you tried so far? You'll find lots of examples on this site and by Googling. – horchler Nov 09 '13 at 17:36
  • possible duplicate of [Implementing explicit Euler method (for ODEs) in MATLAB](http://stackoverflow.com/questions/13063060/implementing-explicit-euler-method-for-odes-in-matlab) – horchler Nov 09 '13 at 17:36
  • @horchler how is this i duplicate? The one you have suggested is for the first order, I have two of those. – John Nov 09 '13 at 18:41
  • @horchler The thing is that I dont know how to start... I dont really know how to setup the I.C or inside the for loop. – John Nov 09 '13 at 18:42
  • 1
    @John You have a vector equation rather than a scalar, but the linked duplicate still applies. – Dang Khoa Nov 09 '13 at 18:42

1 Answers1

0

Our equations are:

u1' = u2
u2' = u1/9 - \pi u1 exp(x/3)(2u2 sin(\pi x) + \pi u1 cos(\pi x))

Now the Euler Method for solving an y' = f(x,y) is:

y_{n+1} = y_{n} + h * f(x_n, y_n)

As MATLAB code, we could write this as:

h = 0.01; % Choose a step size
x = [0:h:2]; % Set up x
u = zeros(length(x),2);
u(1,:) = [1; -1/3]; % Initial Conditions for y

for ii = 2:length(x)
    u(ii,:) = u(ii-1,:) + h * CalculateDeriv(x(ii-1),u(ii-1,:)); % Update u at each step
end

function deriv = CalculateDerivative(x,u)
deriv = zeros(2,1);
deriv(1) = u(2);
deriv(2) = u(1)/9 - pi*u(1)*exp(x/9)*(2*u(2)*sin(pi*x) + pi*u(1)*cos(pi*x))
end
Simon M
  • 166
  • 1
  • 3
  • Where have you used: y_{n+1} = y_{n} + h * f(x_n, y_n)? I have never heard of CalculateDerive? – John Nov 09 '13 at 18:37
  • CalculateDeriv is the function I have defined instead of f. I have used it in the line u = u + h * CalcDeriv – Simon M Nov 09 '13 at 18:53