R3E1W4
R3E1W4

Reputation: 129

Unexpected "function handle with value" returned from secant method function

I am trying to find the root of the function y = exp(2x) + 3x -4, by using the secant method in MATLAB.

I am given the starting values x1=0.5 and x2=0.4, however, if I run my code, I get a "function handle with value" output from MATLAB.

This is my code:

function [f] = fopg1(x)
    f = @(x) exp(2*x)+3*x-4;
    x(1) = 0.5;
    x(2) = 0.4;
    for i=3:5
        x(i) = x(i-1) - (f(x(i-1)))*((x(i-1) - x(i-2))/(f(x(i-1)) - f(x(i-2))));
    end

Can someone explain why my function doesn't run properly?

Upvotes: 0

Views: 374

Answers (1)

Wolfie
Wolfie

Reputation: 30046

You're outputting the wrong variable, namely f when you're expecting to return x. Change the first line to

function [x] = fopg1(x)

If you just want to output the final value, then that's x(5), so

function result = fopg1(x)
    % your function 
    % ... 
    result = x(end);

Currently this might as well be a script, since you've hard-coded the initial guesses, the function, and the maximum iterations (3). If you want to take advantage of this being a function, you might as well input a function handle and initial conditions. The maximum number of iterations would usually be paired with a tolerance, such that you stop if two consecutive x values are close enough.

function x = mySecant( f, x0, n, tol )
%% Find root using secant method
% Inputs: f   - a function handle
%         x0  - 1x2 array of initial guesses
%         n   - maximum number of iterations        
%         tol - tolerance of convergence
    x = x0;
    for i = 3:n+2
        % Stop iterating if converged
        if abs(x(i-2) - x(i-1)) < tol
            break
        end
        % iterate
        x(i) = x(i-1) - (f(x(i-1)))*((x(i-1) - x(i-2))/(f(x(i-1)) - f(x(i-2))));
    end

Again, if you want to just output the converged value then use the x(end) method above.

Called using

x = mySecant( @(x) exp(2*x)+3*x-4, [0.5,0.4], 3, 1e-3 );

Upvotes: 1

Related Questions