Eulers method see also 214 Numerical Simulation of Different
Euler\'s method (see also 2.1.4 Numerical Simulation of Differential Equations - pages 35-37 in text book) for solving the ODE dy/dx = f (x, y) given y(0) entails the approximation of this ODE below: y_i + 1 = y_i + hf(x_i, y_i) Where the domain of x is discretized according to h such that x_i = (i - 1)h at the instep and y_1=y(0). Write a MATLAB script implementing the Euler method to solve the following ODE: dy/dx - 2x^3 with y(0)= 1 and x Element [0, 2]. Plot the solution (y vs. x) and compare it with the analytical solution of the equation.
Solution
You need to implement below both scripts as functions in the MATLAB directory that you work in.
The first script will be the implementation of your ODE, being dy/dx = 2x².
The second function will be used to calculate the Euler approximation for your ODE and will only be different in the inputs you give it.
Write ODE function in MATLAB as:
Function xdot=ODE(t,x)
xdot=2*x^3
end
Now we will implement Euler method:
funnction [t, x] = Euler(f, tinterval, x0, n)
Aproximation of x\' = f(t, x) over tinterval = [t0, tn]
x(t0) =x0 and stepsize dt=(tn-t0)/n
x= zeros(n+1,1);
x(1)= x0;
dt = (tinterval(2) - tinterval(1))/n;
t = tinterval(1):dt:tinterval(2) ;
for k = 1:n
x(k+1)=x(k) + dt*f(t(k),x(k));
end
t = t\';
end
