Search code examples
matlabmathnewtons-method

General Newton Method Function File Matlab


I have very limited knowledge on Matlab and I'm trying to make a general Newton Raphson function but every time it comes up with an error saying there are not enough input arguments. My code needs three inputs, f (the function), c0 (the initial guess) and n (the number of steps). This is my code so far:

function [c] = Q3(f,c0,n)


for i=1:n

c(0)=c0;
f=f(x);
fp=diff(f,x);

c(i)=c(i-1)-subs(f,x,c(i-1))/subs(fp,c(i-1));

end


disp(c)

I have this function written in a script file

g=@(x)(sin((pi.*x)/2)+(1/x)-(10.*x));

I then put this into the command window [c]=Q3(g(x),1,n) hoping it would work but obviously my code needs work. Thanks


Solution

  • This should do the trick, the function g is defined as you stated:

    g=@(x)(sin((pi.*x)/2)+(1/x)-(10.*x));

    but also you should define n and c0, for example:

    clearvars
    
    g=@(x)(sin((pi.*x)/2)+(1/x)-(10.*x));
    
    n=10
    c0=1
    
    c=Q3(g,c0,n)
    

    And in another file you write the function for NR:

    function [c] = Q3(f,c0,n)
    
    h=1e-4;
    c(1)=c0;
    
    for i=1:n 
        g=f(c(i));
        gp=(f(c(i)+h)-f(c(i)-h))/(2*h)
        c(i+1)=c(i)-g/gp
    end
    
    disp(c)
    

    In this case I choose h=1e-4 for the numerical derivative approximation, but you can change it. I suggest h<1e-2.