I'm trying to use the table function, How do I show all the outputs for each iteration?
1 view (last 30 days)
Show older comments
clear all, format long
xl=1.5;xu=3;error=abs(xu-xl);k=0;
number_of_significant_digits=3;pre=0.5*10^(2-number_of_significant_digits);
f=@(x)x^2-3*x+2;
xr=xu;
while abs(error)>pre
xrn=(xl+xu)/2;
if f(xrn)*f(xl)>0
xl=xrn;
else
xu=xrn;
end
k=k+1;
error=(xrn-xr)*100/xrn;
xr=xrn;
end
k=k';
xr=xr';
error=error';
table(k,xr,error,f(xrn))
0 Comments
Answers (1)
Jon
on 5 May 2023
You need to assign your values in the loop to arrays so that they are saved. Could do something like this:
xl=1.5;
xu=3;
error=abs(xu-xl);
k=0;
number_of_significant_digits=3;
pre=0.5*10^(2-number_of_significant_digits);
f=@(x)x^2-3*x+2;
xr=xu;
% preallocate (we don't know size so just estimate)
numVals = 1000;
kvals = zeros(numVals,1);
errorVals = zeros(numVals,1);
xrVals = zeros(numVals,1);
fvals = zeros(numVals,1);
while abs(error)>pre
xrn=(xl+xu)/2;
if f(xrn)*f(xl)>0
xl=xrn;
else
xu=xrn;
end
k=k+1;
error = (xrn-xr)*100/xrn;
xr = xrn;
% save results in arrays
kvals(k) = k;
errorVals(k)=error;
xrVals(k)=xr;
fvals(k) = f(xrn);
end
% put in table, just use values that were actually assigned
table(kvals(1:k),xrVals(1:k),errorVals(1:k),fvals(1:k),'VariableNames',{'k','xr','error','f'})
2 Comments
Jon
on 5 May 2023
Alternatively, you could assign new rows to the table on each iteration like this which may be a little simpler, not sure about efficiency, but probably doesn't matter for this small size problem:
xl=1.5;
xu=3;
error=abs(xu-xl);
k=0;
number_of_significant_digits=3;
pre=0.5*10^(2-number_of_significant_digits);
f=@(x)x^2-3*x+2;
xr=xu;
% initialize table
% this first row will get overwritten anyhow just initialize with zeros
results = table(0,0,0,0,'VariableNames',{'k','xr','error','f'});
while abs(error)>pre
xrn=(xl+xu)/2;
if f(xrn)*f(xl)>0
xl=xrn;
else
xu=xrn;
end
k=k+1;
error = (xrn-xr)*100/xrn;
xr = xrn;
% save results in table
results(k,:) = {k,xr,error,f(xrn)};
end
results
See Also
Categories
Find more on General Physics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!