フィルターのクリア

Plotting the exact and numerical solutions on the same plot

23 ビュー (過去 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 Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by