MATLAB question: Develop code that will implement Euler\'s method for a first-or
ID: 3804147 • Letter: M
Question
MATLAB question:
Develop code that will implement Euler's method for a first-order differential equation defined in a file myode. Use the same conventions as the inbuilt Matlab functions (e.g., ode45 - if your function is called euler, I should be able to run it as [t,y] = euler(@myode,tspan,y0). Your method should refine the step size until you have achieved convergence. As a test function, use dx/dt = -2x with x(0) = 10 . Integrate over t = [0 4].
Modify your Euler's code to implement a general second-order Runge-Kutta method. Use the same test function as above. Solve the test function analytically.
For Euler's and Heun's methods, make a plot showing how the absolute true error varies with step-size (you need to solve the problem by hand to obtain the true error). Do your results agree with your expectations?
Explanation / Answer
I am pasting Matlab program for eular's method and Runge-Kutta method:
1. Eular' Method
a. fine name: eular.m
x0=input(' Enter the initial value of x0:');
y0=input(' Enter the initial value of y0:');
xg=input(' Enter the given value of xg:');
h=input(' Enter the value of step size h:');
n=(xg-x0)/h;
for i=1:n
yg=y0+h*f(x0,y0);
x0=x0+h;
y0=yg;
end
fprintf('The final value of yg=%f',yg);
b. file name: f.m
function y=f(x,y)
y=(x-y*y);
2. Runge-Kutta second order method:
a. file name: rdecond.m
x0=input(' Enter the initial value of x0:');
y0=input(' Enter the initial value of y0:');
xg=input('Enter the given value of xg:');
h=input('Enter the value of step size h:');
n=(xg-x0)/h;
for i=1:n
k1=h*f(x0,y0);
k2=h*f(x0+h,y0+k1);
k=(k1+k2)/2;
yg=y0+k;
x0=x0+h;
y0=yg;
end
fprintf('The final value of yg=%f',yg);
b. file name: f.m
function y=f(x,y)
y=x+y;
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.