0

I have the following matlab code that uses incremental search to find the value of x where there is a sign change. Using the position found, I can calculate xg. The function I am using is fun=(0.01-1)+(x*cot(x)). Once I used the incremental search function, I use a Newton Raphson code to find roots, and if this method fails I use a Bisection algorithm to find the roots.

How would I add all the roots found by the program into a vector?

function [xl,xr]=incsearchnr(fun,xi,xf,dx,tol)

xl=xi;
xr=xi+dx; % dx is a small increment to move along the x-axis 
yr=feval(fun,xr);
yl=feval(fun,xl);

while (sign(yr*yl)) ==1 && xr<xf % once there is a sign change, use that value to find xg, and then use xg to find roots
    xl=xr;
    xr=xl+dx;
    yl=yr;
    yr=feval(fun,xr);
end

    xg=(xl*yr-xr*yl)/(yr-yl); % formula to get our first guess to input in newton raphson method
    [xn,nrfail]=newraphson(fun,xg,xl,xr,tol); % call NR method
    
    if nrfail==1
        [xn,sing]=bisection(fun,xl,xr,yl,yr,tol); % if newton rasphon methods fails, use bisection method
        xold=xnew ; yold=feval(fun,xold);

end
cschlum
  • 25
  • 5
  • Not sure about the code you have provided. But I can answer the question in the text. There are two ways. 1) If you know the number of outputs you are going to get: `allSolutions = nan(1, nOutputs); ...; allSolutions(ii) = currentOutput;`. 2) If you don't know the number of outputs you are going to get: start with `allSolutions = [];` then, each time you find a solution, `allSolutions(end+1) = currentSolution`. PS you can simplify the while loop using e.g. `x = xl:dxo:xr; y = fun(x); s = find(diff(sign(y))); % find where y changes sign;`. – magnesium Oct 17 '22 at 05:53

0 Answers0