Why does using a symbolic function as argument in a function give 'not enough input arguments' error?

3 views (last 30 days)
Zayan Qazi
Zayan Qazi on 21 Nov 2021
Answered: Zayan Qazi on 21 Nov 2021
Context(for numerical methods/optimization experts): I'm creating a function that would perform the numerical root finding method, Bisection, on any given function.
Context(for generalists): I'm creating a function that would take a symbolic function and produce the root of the symbolic function.
The code:
function root = bisection(f, xu, xl, es)
%this function will take a symbolic function,f, and perform bisection on it
%with an initial bracket between [xl,xu] and keep performing bisection
%until the percent relative error, ea, is less or equal to es(stopping
%f is the function on which bisection will be performed
%xu is the upper limit for performing bisection
%xl is the lower limit
%es is the stopping criteria
syms f(x)
fxl = subs(f, x, xl);
while abs(fxr)>es
xr = (xu+xl)/2;
fxr = subs(f, x, xr);
if xr==0
elseif fxr*fxl >0
xl = xr;
xu = xr;
The error:
Not enough input arguments.
Error in bisection (line 4)
fxl = subs(f, x, xl);
I understand that the problem is that subs is not seeing the x variable inside f. Is there any workaround for this?

Accepted Answer

Zayan Qazi
Zayan Qazi on 21 Nov 2021
So I've found out why I was getting that error. It's because I was running the function. When a function that requires input is run with the play button/f5/in the command line, it will naturally throw the error 'not enough inputs' given, since the function hasn't been given any inputs yet. Functions are to be defined and then saved. Not run. They're to be run only when we call them from the command line or a script with inputs/arguments.

More Answers (1)

Paul on 21 Nov 2021
There seems to be more f's than is needed. If the first input to bisection from the caller is a symfun, it should be usable directly as f on the inside of the function
syms g(x)
g(x) = x;
root = bisection(g,2,1,-1)
fxl = 
root = 0
If the input is a sym expression, then use subs
syms g
g = x;
root = bisection1(g,2,1,-1)
fxl = 
root = 0
function root = bisection(f, xu, xl, es)
% syms f(x)
% f(x)=f;
fxl = f(xl) % handle fxr the same way
root = 0;
function root = bisection1(f, xu, xl, es)
fxl = subs(f,symvar(f),xl)
root = 0;

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!