Azzera filtri
Azzera filtri

Multiple plots in one iterative script

1 visualizzazione (ultimi 30 giorni)
Matty Student
Matty Student il 19 Ott 2022
Risposto: Vishesh il 25 Ott 2022
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

Risposte (1)

Vishesh
Vishesh il 25 Ott 2022
  • 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

Categorie

Scopri di più su 2-D and 3-D Plots in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by