1

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

Beth
  • 13
  • 2
  • The code is wrong. `subs` is for symbolic substitution, if you want to evaluate the function, you need to do `f(c(i-1))`. Among other things.... most of the code is wrong. – Ander Biguri Mar 09 '17 at 16:02
  • 1
    Possibly the only thing missing is to declare `x` as a symbol before `f=f(x)` so that this correctly changes `f` from a function into a symbolic expression. – Lutz Lehmann Mar 09 '17 at 16:25
  • @LutzL yes, but NR is a numeric method, so having a NR symbolically is not really a very smart idea. you can solve it with `solve` if you have a symbolic expression. – Ander Biguri Mar 09 '17 at 17:00

1 Answers1

0

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.