Question

In Exercise, use the Runge-Kutta method with the given number n of steps to approximate the solution to the initial-value pro

0 0
Add a comment Improve this question Transcribed image text
Answer #1

MATLAB Script:

close all
clear
clc

f = @(t,y) exp(2/y); % Given ODE
t0 = 0; tf = 2; % Intervals of t
y0 = 2; % Initial condition
n = 4;
h = (tf - t0)/n; % Step Size
t = t0:h:tf;

[t_e, y_e] = ode45(f, [t0, tf], y0); % Exact solution
plot(t_e, y_e), hold on % Plot the exact solution

y = my_euler(t0, y0, tf, h, f);
plot(t, y, 'o-') % Plot Euler's method solution

y = my_imp_euler(t0, y0, tf, h, f);
plot(t, y, '*-') % Plot Improved Euler's method solution

y = my_rk4(t0, y0, tf, h, f);
plot(t, y, '^-'), hold off % Plot RK4 method solution
fprintf('RK4 Method Solution\n-----------------------------------------------------------\n')
fprintf('%-10s%-20s\n', 't(i)', 'y(i)')
for i = 1:length(t)
fprintf('%-10.4f%-20.4f\n', t(i), y(i))
end

xlabel('t'), ylabel('y(t)')
legend('Exact Solution', 'Euler''s Method', 'Improved Euler''s Method', 'RK4 Method', 'Location', 'northwest')
title('Solution of ODE')

function y = my_euler(t0, y0, tf, h, f)
y(1) = y0;
t = t0:h:tf;
for i = 1:length(t)-1
y(i+1) = y(i) + h*f(t(i), y(i)); % Euler Update
end
end

function y = my_imp_euler(t0, y0, tf, h, f)
y(1) = y0;
t = t0:h:tf;
for i = 1:length(t)-1
f1 = f(t(i), y(i));
f2 = f(t(i) + h, y(i) + h*f1);
y(i+1) = y(i) + (h/2)*(f1 + f2); % Improved Euler's Update
end
end

function y = my_rk4(t0, y0, tf, h, f)
y(1) = y0;
t = t0:h:tf;
for i = 1:length(t)-1
k1 = f(t(i), y(i));
k2 = f(t(i) + 0.5*h, y(i) + 0.5*h*k1);
k3 = f(t(i) + 0.5*h, y(i) + 0.5*h*k2);
k4 = f(t(i) + h, y(i) + k3*h);
y(i + 1) = y(i) + (1/6)*(k1 + 2*k2 + 2*k3 + k4)*h; % RK4 Update
end
end

Output:

Command Window RK4 Method Solution t(i) Π£(i) 0.0000 2.0000 0.5000 3.1046 1.0000 3.9855 4.7755 1.5000 2.0000 5.5135 f > |

Plot:

Solution of ODE Exact Solution Eulers Method -Improved Eulers Method A-RK4 Method 5.5 5 4.5 3.5 3 2.5 0.6 0.8 1.2 1.4 1.8 0

Add a comment
Know the answer?
Add Answer to:
In Exercise, use the Runge-Kutta method with the given number n of steps to approximate the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT