Multiple plots in one iterative script

조회 수: 3 (최근 30일)
Matty Student
Matty Student 2022년 10월 19일
답변: Vishesh 2022년 10월 25일
I'm trying to plot two graphs that plot the iterations and respective errors. I'm not sure what I'm doing wrong. 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개)

Vishesh
Vishesh 2022년 10월 25일
  • Store the values of "AppErr" and "TrueErr" of each iteration together.
  • Plot the graph outside of the iteration.
  • You can use this code for the reference.
function BisectMeth(xL, xU, es, itermax)
f = @(x)exp(-x)-x;
xR = xU;
fL = f(xL);
AppErr=[];
TrueErr=[];
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
AppErr = [AppErr (xR*ea)/100];
TrueErr = [TrueErr 0.56714329 - xR];
end
iter=1:itermax;
figure(1);
plot(iter,TrueErr);
disp(iter);
disp(TrueErr);
xlabel('Number of Iterations');
ylabel('True Error');
figure(2);
plot(iter, AppErr);
xlabel('Number of Iterations');
ylabel('Approximate Error');
fprintf('Root is %f\n', xR)
fprintf('Approximate error is %f\n',AppErr)
fprintf('True error is %f\n', TrueErr)
end

카테고리

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