The problem is simple, I'm trying to graph the Global Error of Euler's method vs. the step size 'h' but I cannot end up with a line, only points are graphed.
Let 'm' be a natural number such as m=2,4,6...100. The step size h is 1/m.
We want to draw a graph with GLOBAL ERROR vs h depending on m.
%Experiment
%u'=1/(1+t)^2 u(0)=0 en el intervalo [0,1]
exact=0.5; %exact value
f=@(t,u) 1./(1+t).^2;
t0=0;
tfinal=1;
u0=0;
for m=2:2:100
hold on
h=1./m; %step (variable)
[vt,vsol]=ode1(t0,h,tfinal,f,u0); %ode1 is Euler's method solver
approx=vsol(end);
errorglobal = approx - exact;
loglog(errorglobal, h, '-o')
set(gca, 'XScale', 'log', 'YScale', 'log');
grid on
hold off
end

 채택된 답변

Star Strider
Star Strider 2020년 12월 21일

1 개 추천

I can’t run your code, so you’ll have to test this edit of it.
Try this:
%Experiment
%u'=1/(1+t)^2 u(0)=0 en el intervalo [0,1]
exact=0.5; %exact value
f=@(t,u) 1./(1+t).^2;
t0=0;
tfinal=1;
u0=0;
errorglobalv = nan(1,50);
hv = nan(1,50);
mv = 0;
for m=2:2:100
mv = mv + 1;
h=1./m; %step (variable)
[vt,vsol]=ode1(t0,h,tfinal,f,u0); %ode1 is Euler's method solver
approx=vsol(end);
errorglobal = approx - exact;
hv = h(mv); % Store Results In Vector
errorglobalv(mv) = errorglobal; % Store Results In Vector
end
figure
loglog(errorglobalv, hv, '-o')
set(gca, 'XScale', 'log', 'YScale', 'log');
grid on
hold off
The ‘mv’ counter is required because otherwise the plot will not be continuous.

댓글 수: 4

Andrés Pacheco Marín
Andrés Pacheco Marín 2020년 12월 21일
편집: Andrés Pacheco Marín 2020년 12월 21일
I tried the code and got this error:
Index exceeds the number of array elements (1).
Error in filename (line 19)
hv = h(mv); % Store Results In Vector
The thing is that with my code I get good results, and can even display correct values of m, h and errorglobal variables, but when I try to graph the solution it only draws points, not the line. Let me attach the graph:
This is the problem of not being able to test code before I post it.
That line should be:
hv(mv) = h; % Store Results In Vector
I don’t know how I missed that.
Andrés Pacheco Marín
Andrés Pacheco Marín 2020년 12월 21일
Wow, it works. So simple, yet effective.
So, let me get this straight:
  1. First you set a vector of 50 NaN values which you will fill later in the loop.
  2. You set your initial iteration variable mv=0.
  3. Each iteration result is stored in those vectors you set at the beginnig.
  4. You draw the vector instead of 50 individual points, and that's why you get the line.
I think I get the idea even with my vague explanation. Many thanks!
Star Strider
Star Strider 2020년 12월 21일
Correct on all points!
As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

태그

질문:

2020년 12월 21일

댓글:

2020년 12월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by