Fixing a plot to show a horizontal line instead of a point

1 回表示 (過去 30 日間)
Left Terry
Left Terry 2024 年 12 月 31 日
編集済み: Torsten 2024 年 12 月 31 日
Hello. First of all I don't know if my code is correct for the specific task, especially for the error calculations. My problem is that i get a point on the last graph on the errors figure but i need a horizontal line. Why does this happen ?
%--- Exercise 1 - A
%--- Solving the diff. eqn. N'(t) = N(t) - c*N^2(t) with c = 0.5 using
%--- Euler's method, Runge - Kutta method, and predictor-corrector method, and comparing in graph.
%--- I have four initial values for N0.
clc, clear all, close all
tmax = 100;
t = [0:tmax];
c = 0.5;
h = 0.1;
f = @(t,N) N - c*N.^2;
N0 = [0.1 0.5 1.0 2.0];
L = length(t)-1;
N = zeros(1,L);
for i = 1:length(N0)
%--- Exact solution ---
[T,n] = ode45(f,t,N0(i));
figure(1)
subplot(2,2,i), plot(T,n), hold on
title({'N'' = N - cN^2',sprintf('c = %.1f, N_0 = %.1f',c, N0(i))}),xlabel('t'), ylabel('N(t)'), hold on
%--- Euler's method ---
for j = 1:L
NE(1) = N0(i);
NE(1,j+1) = NE(j) + h*f(':',NE(j));
ErrorEuler(j) = abs(n(j) - NE(j))/n(j)*100;
end
plot(t,NE,'r-.'), hold on
%--- Runge - Kutta method ---
for j = 1:tmax
NRK(1) = N0(i);
K1 = f(t(j),NRK(j));
K2 = f(t(j) + h*0.5, NRK(j) + h*K1*0.5);
K3 = f(t(j) + h*0.5, NRK(j) + h*K2*0.5);
K4 = f(t(j) + h, NRK(j) + h*K3);
NRK(j+1) = NRK(j) + h*((K1 + K4)/6 + (K2 + K3)/3);
ErrorRK(j) = abs(n(j) - NRK(j))/n(j)*100;
end
plot(t,NRK,'b.'), legend({'Exact solution','Euler''s method','Runge - Kutta'},'Location','Southeast')
figure(2)
subplot(2,2,i)
plot(NE(1:end-1),ErrorEuler,'.')
hold on
plot(NRK(1:end-1),ErrorRK,'-.')
title({'N(t) vs. Error',sprintf('N_0 = %.1f',N0(i))}), xlabel('N(t)'), ylabel('Error (%)')
legend({'Euler','Runge - Kutta'})
end

回答 (1 件)

Torsten
Torsten 2024 年 12 月 31 日
移動済み: Torsten 2024 年 12 月 31 日
N(t) = 2 for all t, and the error is 0 %. So plotting a line (vertical or horizontal) would be wrong in the case N_0 = 2 - you only get a single point.
  8 件のコメント
Left Terry
Left Terry 2024 年 12 月 31 日
@Torsten I tried it and it didn't work.
Torsten
Torsten 2024 年 12 月 31 日
編集済み: Torsten 2024 年 12 月 31 日
@Left Terry The problem states tthat we have to use h = 0.1.
But you use h = 1 in the ode45 calculation:
tmax = 100;
t = [0:tmax]
t = 1×101
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
So either you use h = 0.1 or h = 1 in both calculations.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeNumeric Solvers についてさらに検索

製品


リリース

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by