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

3 visualizzazioni (ultimi 30 giorni)
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
%criteria).
%
%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)
f(x)=f;
fxl = subs(f, x, xl);
while abs(fxr)>es
xr = (xu+xl)/2;
fxr = subs(f, x, xr);
if xr==0
break
elseif fxr*fxl >0
xl = xr;
else
xu = xr;
end
end
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?

Risposta accettata

Zayan Qazi
Zayan Qazi il 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.

Più risposte (1)

Paul
Paul il 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 = 
1
root = 0
If the input is a sym expression, then use subs
syms g
g = x;
root = bisection1(g,2,1,-1)
fxl = 
1
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;
end
function root = bisection1(f, xu, xl, es)
fxl = subs(f,symvar(f),xl)
root = 0;
end

Community Treasure Hunt

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

Start Hunting!

Translated by