Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Matlab, iteration with newton's method, noobs & errors

  1. Apr 2, 2008 #1

    I have to describe the famous newton-rapshon algorithm for finding a root of the function
    this is what i came up with, i aint not familiar with matlab and programming at all, so this is somewhat a melt from a lot of matlab tutorials, I dont master the code, but what's really a challenge is understanding the errors
    function x = newton(fun,dfun,x0,tol,Nmax)
    x = x0;
    f(x) = feval(fun,x);
    df(x)= feval(dfun,x);
    steps = 0;

    re = tol;
    myrel = 1;
    while myrel > re && (steps < Nmax)
    xold = x;
    x = x - f(x)/df(x);
    steps = steps + 1;
    myrel = abs((x-xold)/x);
    if myrel <= re
    disp( 'Zero found at' )
    disp( x )
    disp( 'Zero NOT found' )

    when i test it, i find 2 very strange facts

    fact 1: it cannot handle non-integer, if I want to test the function in the prompt with sin and cos and x0=3 , it stops on the first iteration: 3,14255...
    this is the error:
    attempted to acces f(3.14255); index must be a positive inter or logical

    My idea: i thought matlab had no problems at all with any kind of number, in c++(also a big noob at that) u have to declarate everything, but not so in matlab yes?)

    and fact2
    i only tested the function with sin, cos and 3

    when i test it with a simple Polynomial, let's say x²-2 for finding the value of square root of 2 it gives an error in the second line: f(x) = feval...

    how can that line work with the first example and not with a simple polynomial in x,

    can someone get me on track
  2. jcsd
  3. Apr 7, 2008 #2
    bump ? anyone ??
  4. Apr 7, 2008 #3


    User Avatar
    Science Advisor
    Homework Helper

    It sounds like f is set up as an array instead of a function.
  5. Apr 12, 2008 #4
    The problem is that when you write f(x), Matlab treat this as an vector. So the solution is to write something like f=feval(...) inside the while loop (and remove the line f(x)=... and similar for df(x)
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook