• Write a MATLAB program to solve the following initial value problem using Euler’s
method
𝒅𝒚
= 𝒙𝟐 − 𝒚 𝒘𝒊𝒕𝒉 𝒕𝒉𝒆 𝒄𝒐𝒏𝒅𝒊𝒕𝒊𝒐𝒏 𝒚(𝟎) = 𝟏.
𝒅𝒙
Determine y(0.05) when h =0.01.
MATLAB CODE:
clc;
clear;
% Given parameters
h = 0.01; % step size
x0 = 0; % initial x
y0 = 1; % initial y
x_end = 0.05; % target x value
% Number of steps
n = (x_end - x0)/h;
% Initialization
x = x0;
y = y0;
% Euler's method loop
for i = 1:n
y = y + h*(x^2 - y);
x = x + h;
end
% Display result
fprintf('The approximate value of y(0.05) is %.6f\n', y);
• Write a MATLAB program to determine the value of y when x =0.07 using Modified
Euler’s method
𝒅𝒚
= 𝒙𝟐 + 𝒚 𝒘𝒊𝒕𝒉 𝒕𝒉𝒆 𝒄𝒐𝒏𝒅𝒊𝒕𝒊𝒐𝒏 𝒚(𝟎) = 𝟎. 𝟓
𝒅𝒙
Take h =0.05.
MATLAB CODE:
% Modified Euler's Method for dy/dx = x^2 + y
clc;
clear;
% Initial conditions
x = 0;
y = 0.5;
% First step with h = 0.05
h = 0.05;
f = @(x,y) x^2 + y;
% Predictor
yp = y + h * f(x,y);
% Corrector
y = y + (h/2) * ( f(x,y) + f(x+h,yp) );
x = x + h;
% Second step with h = 0.02 to reach x = 0.07
h = 0.02;
% Predictor
yp = y + h * f(x,y);
% Corrector
y = y + (h/2) * ( f(x,y) + f(x+h,yp) );
x = x + h;
% Display result
fprintf('The approximate value of y(0.07) is %.6f\n', y);
• Write a MATLAB program to solve the following initial value problem using 2nd order
Runge-Kutta method
𝒅𝒚
= 𝒙𝟐 − 𝒚 𝒘𝒊𝒕𝒉 𝒕𝒉𝒆 𝒄𝒐𝒏𝒅𝒊𝒕𝒊𝒐𝒏 𝒚(𝟎) = 𝟏.
𝒅𝒙
Determine y(0.05) when h =0.01.
% Second Order Runge-Kutta Method for dy/dx = x^2 - y
clc;
clear;
% Given parameters
h = 0.01; % step size
x = 0; % initial x
y = 1; % initial y
x_end = 0.05; % target x value
% Define the function
f = @(x,y) x^2 - y;
% Number of steps
n = (x_end - x)/h;
% RK2 loop
for i = 1:n
k1 = h * f(x, y);
k2 = h * f(x + h, y + k1);
y = y + 0.5 * (k1 + k2);
x = x + h;
end
% Display result
fprintf('The approximate value of y(0.05) using RK2 is %.6f\n', y);
• Write a MATLAB program to determine the value of y when x =0.07 using 4th order Runge
Kutta method
𝒅𝒚
= 𝒙𝟐 + 𝒚 𝒘𝒊𝒕𝒉 𝒕𝒉𝒆 𝒄𝒐𝒏𝒅𝒊𝒕𝒊𝒐𝒏 𝒚(𝟎) = 𝟎. 𝟓
𝒅𝒙
Take h =0.05.
% Fourth Order Runge-Kutta Method for dy/dx = x^2 + y
clc;
clear;
% Initial conditions
x = 0;
y = 0.5;
% Define the function
f = @(x,y) x^2 + y;
% First step with h = 0.05
h = 0.05;
k1 = h * f(x, y);
k2 = h * f(x + h/2, y + k1/2);
k3 = h * f(x + h/2, y + k2/2);
k4 = h * f(x + h, y + k3);
y = y + (1/6) * (k1 + 2*k2 + 2*k3 + k4);
x = x + h;
% Second step with h = 0.02
h = 0.02;
k1 = h * f(x, y);
k2 = h * f(x + h/2, y + k1/2);
k3 = h * f(x + h/2, y + k2/2);
k4 = h * f(x + h, y + k3);
y = y + (1/6) * (k1 + 2*k2 + 2*k3 + k4);
x = x + h;
% Display result
fprintf('The approximate value of y(0.07) using RK4 is %.6f\n', y);