Plotting the exact and numerical solutions on the same plot

조회 수: 28 (최근 30일)
Bas123
Bas123 2023년 5월 1일
댓글: Bas123 2023년 5월 1일
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