I'm trying to implement, in Matlab, the following methods for root finding:

Fixed point iteration with g(x) = x-αf(x) Newton's method, The secant method, Steffensen's method.

For f(x)=x^2+x-1, with x0 = 1

However, since I haven't used Matlab before, my loops for each algorithm are full of bugs. Can someone please show me a correct way to do them?

  • $\begingroup$ @Moo Yes I did, but still feel very confused. Some of them construct a matrix for the loop, and others didn't. $\endgroup$
    – Hanfei Lin
    Commented Jan 29, 2021 at 19:11
  • $\begingroup$ rosettacode.org/wiki/Roots_of_a_function $\endgroup$
    – caverac
    Commented Jan 29, 2021 at 19:12

1 Answer 1


I quickly threw together a code that uses Newton's method, I hope it's correct. In any case you should be able to see how the syntax of Matlab works.

f = @(x) x^2 + x -1; % function
df = @(x) 2*x + 1;   % derivative needed for newtons method

e = 10^-7;           % error margin
x = 0;               % initial value

n = 0;               % number of iterations

while abs(f(x)) > e  % apply newton's method until error small enough
    x = x - (f(x)/df(x));
    n = n+1;

fprintf('root: %i\n', x)
fprintf('number of iterations: %i\n', n)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .