0

I'm working on my own Matlab code for the bisection method, and have defined an anonymous function I am trying to find the root for. It produces a simple graph and I know it could easily find the root if it would run properly.

When my code gets up to evaluating the function at a given x value, it returns:

Error using feval
Function to evaluate must be represented as a string scalar, character vector, or
function_handle object.

Error in bisection (line 3)
fa = feval(f, a);

My full code is:

function m=bisection(f,a,b,imax,tol)

    fa = feval(f, a);
    fb = feval(f, b);
    i=0;

    if fa*fb>0
        disp('No root here: pick a new interval')
        return
    end
    while abs(b-a) >= tol
        i = i + 1;
        m=(a+b)/2;
        fm = feval(f, m);
        if fa*fb<0
            b = m;
        else
            a = m;
        end
        abs(fm);
    end
    % Show the last approximation considering the tolerance
    w = feval(f, m);
    fprintf('\n x = %f produces f(x) = %f \n %i iterations\n', m, fm, i-1);
    fprintf(' Approximation with tolerance = %f \n', tol);
end

With my function being:

function [T] = freezing(x)

alpha = 0.138*10^-6;
Ti = 20;
Ts = -15;
t = 60*60*24*60;
tol = 10^-13;

%x = linspace(0,3);

T = @(x) (Ti-Ts)*erf(x./(2*sqrt(alpha*t)))+Ts;
dT = @(x) (Ti-Ts)*(1/sqrt(pi*alpha*t))*exp(-x.^2./(4*alpha*t));
T = T(x);
end

I'm really not sure what the issue is here – in my command window, I can easily input x values and get output. Any suggestions are much appreciated!

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • Does this answer your question? [What is a function handle and how is it useful?](https://stackoverflow.com/questions/796935/what-is-a-function-handle-and-how-is-it-useful) – Pranav Hosangadi Sep 10 '20 at 16:01
  • I am passing freezing(x) to f in bisection. When I evaluate freezing(#), it works out fine in the command window. a and b are predefined as in the example you sent me, so I still am not sure what the solution is. – liveFreeOrπHard Sep 10 '20 at 16:41
  • That was it!! Thank you Pranav! If you post that as a solution, I'll mark this as solved. :-) – liveFreeOrπHard Sep 10 '20 at 16:46

1 Answers1

1

feval needs f to be a function handle. When you call bisection, I suspect you're passing the result of freezing to bisection instead of the function handle to freezing

You need to do bisection(@freezing, ...) instead of bisection(freezing(...), ...)

The @freezing creates a function handle that is passed to bisection. Doing the latter passes the result of freezing to bisection.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70