I'm trying to use the table function, How do I show all the outputs for each iteration?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Jon
2023-5-5
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 个评论
Jon
2023-5-5
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
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!