Impact-Site-Verification: dbe48ff9-4514-40fe-8cc0-70131430799e

Search This Blog

MATLAB Program for Newton-Raphson method | .m file

Program:



%% Newton-raphson Method %%

clc;

display('**--------- Newton-Raphson method (Single function)---------**');

display('==========================================');

display( '  ');

%% Function Inputs %%

format long

syms x;

f=input('Enter the function {f(x)}           ');

fprime=diff(f);

%% Find true root values & display them

S=solve(f,'Real',true);

S=double([S]);

S=array2table(S,'VariableNames',{'X_true'  });

display('  ');

display('#------------Hint Roots !--------------# ');

display(S);

display('#-----------------------------------------# ');

%% Parameters Inputs {inital Guesses,maximum iterations,minimum errors}

xi=input('Enter the initial guess {xi}          :');

xt=input('Enter the true value {xt}          :');

etmin=input('Enter the minimum true error required  {Et%}          :');

eamin=input('Enter the minimum approximate error required  {Ea%}          :');

imax=input('Enter the maximum number of iterations  {i}          :');

%% Main algorithm %%

i=2;

m=1;

xold=xi;

A=[1 xi double(subs(f,{x},xi)) nan nan];

while m==1

    xold=xi;

    f0=double(subs(f,{'x'},xold));

    fprime0=double(subs(fprime,{'x'},xold));

    xi=xold-((f0)/(fprime0));

    et=abs((xt-xi)/(xt))*100;

    ea=abs((xi-xold)/(xi))*100;

     A=[A;i xi double(subs(f,{x},xi)) et ea];

    i=i+1;

  if fprime0==0

        m=0;

        display('The method can not be continued ;Hint:  try another initial guess');

  end

    if ea<eamin || et<etmin || i>imax

        m=0;

    end

    %% Outputs %%

    A=double(A);

T=array2table(A,...

    'VariableNames',{'Iteration' 'xi' 'Fxi' 'et' 'ea' });

plot(A(:,1),A(:,4),'linewidth',2)

xlabel('Iteration')

ylabel('Et%')

grid

title('Et% versus Iterations Plot')

uT=uitable('Data',T{:,:},'ColumnName',T.Properties.VariableNames,'RowName',T.Properties.RowNames,...

 'fontsize',13,'unit','normalized', 'Position',[0, 0, 1, 1]);

end



No comments

Popular Posts

Followers