How can I create a table containing all iterations?

3 views (last 30 days)
I need to have a table containing iter, xr, func(xr), and es for each iteration of the loop. I have tried listing them as arrays but cannot seem to get that to work.
function[root,ea,iter]=secant(func,delta,xr,es,maxit,varargin)
if nargin<3,error('atleast 3 input arguments required'),end
if nargin<4|isempty(es),es=0.0001;end
if nargin<5|isempty(maxit),maxit=50;end
iter=0;
while (1)
xrold=xr;
xr=xr-((delta*xr*func(xr))/(func(xr+(delta*xr))-func(xr)));
iter=iter+1;
if xr~=0, ea=abs((xr-xrold)/xr)*100;end
if ea<=es|iter>=maxit,break,end
funcxr=func(xr);
end
root=xr;

Accepted Answer

Ayush Gupta
Ayush Gupta on 17 Sep 2020
To create a table, store every instance of iter, xr, func(xr), and es at each iteration into a list that is globally and append each iteration to it. Refer to the following code on how to do it:
function[root,ea,iter]=secant(func,delta,xr,es,maxit,varargin)
if nargin<3,error('atleast 3 input arguments required'),end
if nargin<4|isempty(es),es=0.0001;end
if nargin<5|isempty(maxit),maxit=50;end
itr =[];
xr =[];
func_xr =[];
es =[];
iter=0;
while (1)
xrold=xr;
xr=xr-((delta*xr*func(xr))/(func(xr+(delta*xr))-func(xr)));
iter=iter+1;
if xr~=0, ea=abs((xr-xrold)/xr)*100;end
if ea<=es|iter>=maxit,break,end
funcxr=func(xr);
itr(i) = iter;
xr(i) = xr;
func_xr(i) = funcxr;
es(i) = es;
end

More Answers (0)

Community Treasure Hunt

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

Start Hunting!