Plotting the exact and numerical solutions on the same plot
조회 수: 28 (최근 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!
댓글 수: 0
채택된 답변
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 Center 및 File Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!