SHARE
TWEET

Newton-Raphson MATLAB

a guest Feb 26th, 2020 94 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.  
  3. function newton(f,df,x0,tol,Nmax)
  4.  
  5.     syms x;%Setting x to be a symbolic variable
  6.  
  7.     %Defining the variables
  8.  
  9.     %f=input('Enter your function here: ');
  10.     %df=input('Enter your differentiated function here: ');
  11.     %x0=input('Enter your initial estimation (if unknown, set as 0): ');
  12.     %Nmax=input('Enter your max number of iterations here ');
  13.     %tol=input('Enter your tolerance ');
  14.  
  15.     err=tol+1; %Sets error as larger than the tol to initiate the while loop
  16.     n=0; %Creates the iteration counter
  17.    
  18.     if df==0;
  19.         error('The differential of your function is 0, therefore iterations cannot begin.')
  20.     end
  21.    
  22.     while err>tol;
  23.  
  24.         n=n+1;
  25.  
  26.         fv=subs(f,x,x0);
  27.         fdv=subs(df,x,x0);
  28.         x1=x0-((fv)/fdv);
  29.  
  30.         err=abs(x1-x0);
  31.         x0=x1;
  32.        
  33.         if n>Nmax;
  34.             error('The maximum number of iterations has been reached, therefore a solution has not been found.');
  35.         end
  36.  
  37.  
  38.         if err<tol;
  39.             break
  40.         end
  41.  
  42.     end
  43.     fprintf('The root of your function is: %g \n', x0)
  44.     fprintf('This took %d iterations to reach', n)
  45.  
  46. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top