필터 지우기
필터 지우기

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

조회 수: 3 (최근 30일)
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?

채택된 답변

Zayan Qazi
Zayan Qazi 2021년 11월 21일
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.

추가 답변 (1개)

Paul
Paul 2021년 11월 21일
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

카테고리

Help CenterFile Exchange에서 Conversion Between Symbolic and Numeric에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by