Plotting the exact and numerical solutions on the same plot

23 次查看(过去 30 天)
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!

采纳的回答

Simon Chan
Simon Chan 2023-5-1
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Ordinary Differential Equations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by