[Math] Help with secant method using MATLAB

MATLAB

function Problem1 = SecantMethod()
a=input('enter function:','s');
f=inline(a)
x(1)=input('enter first guess: ');
x(2)=input('enter second guess: ');
n=input('enter tolerance: ');
iteration=0;
i=2;

while (abs(x(i))>0.00001)
    x(i+1)=x(i)-f(x(i))*(x(i)-x(i-1))/(f(x(i)-f(x(i-1))));
    if (f(x(i+1))~=0)
        i=i+1;
        iteration=iteration+1
        root=x(i)
        break
    else
        root=x(i)
        iteration=iteration
        break
        break
    end
end

When I run this, the loop stops correctly (I think).
But it displays wrong number.
Following is simple inputs to MATLAB:
a= 3*x+4
f(x) = 3*x+4
x(1) = -2
x(2) = -1
loop starts:
x(3) = -1.1429 <—–should be the wrong answer, I should get -4/3 as my root.
iteration count = 1 <—– which is correct, because the iteration should be 1.

I think there should be something wrong in my nested while loop, or the condition for the while loop (abs(x(i))>0.00001)

Any help will be appreciated.

Best Answer

Very simple, you have a misplaced parenthesis!

Your demoninator reads

(f(x(i)-f(x(i-1))))

It should read

(f(x(i))-f(x(i-1)))
       ^-- close your f!

I have cleaned up your code as well:

a=input('enter function:','s');
f=inline(a)
x(1)=input('enter first guess: ');
x(2)=input('enter second guess: ');
tol=input('enter tolerance: ');
iteration=0;
i=2;
eps = 1e10;

while (abs(eps) > tol)
    x(i+1)=x(i)-f(x(i))*(x(i)-x(i-1))/(f(x(i))-f(x(i-1)));
    eps = x(i+1)-x(i);
    i = i+1;
    x(i)
end
Related Question