Multiple Plots in One Iterative Script

조회 수: 3 (최근 30일)
Matty Student
Matty Student 2022년 10월 19일
답변: Bjorn Gustavsson 2022년 10월 19일
I am trying to plot two graphs in this iterative process. Thanks in advance.
function BisectMeth(xL, xU, es, itermax)
f = @(x)exp(-x)-x;
xR = xU;
fL = f(xL);
for iter = [1:itermax]
xRold = xR;
xR = (xL +xU)/2;
fR = f(xR);
if xR ~= 0
ea = abs((xR-xRold)/xR)*100;
end
check = fL*fR;
if check <0
xU = xR;
else
if check > 0
xL = xR;
fL = fR;
else
ea = 0;
end
end
if ea < es
break
end
if iter == itermax && ea > es
disp('Max # of iterations reached before acheiving prescribes tolerance')
end
iter = [0:itermax]
AppErr = (xR*ea)/100;
TrueErr = 0.56714329 - xR;
figure(1);
plot(iter,TrueErr);
xlabel('Number of Iterations');
ylabel('True Error');
figure(2);
plot(iter, AppErr);
xlabel('Number of Iterations');
ylabel('Approximate Error');
end
fprintf('Root is %f\n', xR)
fprintf('Approximate error is %f\n',AppErr)
fprintf('True error is %f\n', TrueErr)
end

답변 (1개)

Bjorn Gustavsson
Bjorn Gustavsson 2022년 10월 19일
If you want all the points for each iteration in the 2 figures, then you will have to insert a hold on after each plotting command:
figure(1);
plot(iter,TrueErr,'.');
hold on
xlabel('Number of Iterations');
ylabel('True Error');
figure(2);
plot(iter, AppErr,'.');
hold on
xlabel('Number of Iterations');
ylabel('Approximate Error');
You might also have to set:
axis auto
This is if you want to see how the iteration proceeds, which is sometimes convenient/soothing/necessary/interesting.
But this is a clumsy way to go about this if you only want to see how the iteration process worked after it finished. For this case it is better to store away everyting you want to look at in arrays and plot everyting after the end of the iteration. Perhaps something like:
AppErr = (xR*ea)/100;
TrueErr = 0.56714329 - xR;
TruErrAll(iter) = Truerr;
AppErrAll(iter) = (xR*ea)/100;
end
figure(1);
plot(TrueErrAll);
xlabel('Number of Iterations');
ylabel('True Error');
figure(2);
plot(AppErrAll);
xlabel('Number of Iterations');
ylabel('Approximate Error');
I bloody well hope I guessed close enough...
HTH

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by