Plotting the exact and numerical solutions on the same plot

18 views (last 30 days)
I am working on a numerical analysis problem where I need to draw the exact and numerical solutions on the same figure. The numerical method used is the Runge-Kutta method of order 4. Here is my code.
function [t, x] = RK4Method(f, x_0, t_initial, t_m, n)
%time step
h = (t_m - t_initial) / n;
%arrays for t and x
t = linspace(t_initial, t_m, n+1);
x = zeros(1, n+1);
x(1) = x_0;
%RK4 iterations
for i = 1:n
k1 = h * f(t(i), x(i));
k2 = h * f(t(i) + h/2, x(i) + k1/2);
k3 = h * f(t(i) + h/2, x(i) + k2/2);
k4 = h * f(t(i) + h, x(i) + k3);
x(i+1) = x(i) + 1/6 * (k1 + 2*k2 + 2*k3 + k4);
end
Here is the command that I used to draw the numerical solution.
f = @(t, x) (x-t^2+1);
[t, x] = RK4Method(f, 0.5, 0, 2, 200);
plot(t, x);
xlabel('time');
ylabel('x');
The code used to draw the exact solution is given below.
fplot(@(t) (t^2+2*t+1-(1/2)*e^t, [0 2])
Could someone please help me with drawing the two solutions on the same plot? Thank you!

Accepted Answer

Simon Chan
Simon Chan on 1 May 2023
Just add hold on
f = @(t, x) (x-t^2+1);
[t, x] = RK4Method(f, 0.5, 0, 2, 200);
plot(t, x);
xlabel('time');
ylabel('x');
hold on; % Add this
fplot(@(t) t.^2+2*t+1-(1/2)*exp(t), [0 2],'r--','LineWidth',4); % <--- Modify this

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!