1 view (last 30 days)

Show older comments

function [r k] = root_finder(f,x0,kmax,tol)

x1 = x0; %initial x1

%for loop for x1 from 2 to kmax as intial value x1 is given

for i = 2 : kmax

%evaluating function f @x1 and comparing with tolerance given

if tol > abs(feval(f,x1))

r = x1; % if |f(xk)| < tol then we have to stop

k = i;

break;

else

x1 = x1 + 0.01; %incrementing x1 with 0.01

end

end

end %function ends

J. Alex Lee
on 8 Sep 2020

You want to save the history of x1? It would only make sense if you wanted to also save the histories of the function value f (which you are trying to zero).

Typically, you would use "r" to denote the residual, or function value, so

function [rList,xList,k] = root_finder(f,x1,kmax,tol)

for k = 1 : kmax

xList(i) = x1;

% evaluating function f @x1 and comparing with tolerance given

rList(i) = feval(f,x1);

if tol > abs(r(i))

break;

end

x1 = x1 + 0.01; %incrementing x1 with 0.01

end

end %function ends

Note that this is an objectively bad root-finding algorithm.

Also note that if your function f accepts vector x, then you could also do

xList = (x0:0.01:xEnd)

rList = f(xList)

[rBest,idxBest] = min(abs(rList))

xBest = xList(idxBest)

Ayush Gupta
on 11 Sep 2020

The history of tolerance and corresponding x values can be stored if we treat them as vectors and in each iteration of for loop the value at that point is stored. Refer to the following code to see how it works:

function [r, k] = root_finder(f,x0,kmax,tol)

x1 = x0; %initial x1

%for loop for x1 from 2 to kmax as intial value x1 is given

for i = 2 : kmax

%evaluating function f @x1 and comparing with tolerance given

r(i) = abs(feval(f,x1));

k(i) = x1;

% if |f(xk)| < tol then we have to stop

if tol >r(i)

break;

end

x1 = x1 + 0.01; %incrementing x1 with 0.01

end

end %function ends

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

Start Hunting!