Calling a function within another function

조회 수: 8 (최근 30일)
Brandon Macleod
Brandon Macleod 2018년 2월 7일
댓글: Brandon Macleod 2018년 2월 7일
So I'm writing a bisection method. The beginning of the method looks like this.
function root = Bisect ( xl , xu , eps , imax, f )
i = 1;
fl = f(xl);
So I pass in xl (note that l is the letter L and not a one) when I call this function and it then calls the function f. Here's my function f:
function y = f(x)
y = (pi*x^2)*((3*4.1 - x)/3);
end
The problem is that I called the bisection function with the input "Bisect(0, 4.1, 0.0001, 20, f)" and I keep getting this error:
>> Bisect(0, 4.1, 0.0001, 20, f)
Not enough input arguments.
Error in f (line 3)
y = (pi*x^2)*((3*4.1 - x)/3);
So what am I doing wrong?

채택된 답변

Steven Lord
Steven Lord 2018년 2월 7일
That tries to call the function f with 0 inputs and pass the value returned by that call into the Bisect function as the fifth input. You instead want to pass a function handle to f into the Bisect function as the fifth input, so that later on Bisect can call f using that function handle.
Bisect(0, 4.1, 0.0001, 20, @f)
You'd see the same behavior if you did something like:
fzero(sin, 1) % will error because sin needs 1 input
instead of:
fzero(@sin, 1)
or:
fzero(@(x) sin(x), 1)

추가 답변 (1개)

Matt J
Matt J 2018년 2월 7일
편집: Matt J 2018년 2월 7일
Use '@' to specify a handle to f(),
Bisect(0, 4.1, 0.0001, 20, @f)

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by