Multiple plots in one iterative script

1 次查看(过去 30 天)
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