how to pass a function with internally set parameters as an input to another function

조회 수: 2(최근 30일)
Collin Schmidt 2021년 7월 25일
댓글: Collin Schmidt 2021년 7월 25일
Hello,
I am using a function with internally defined parameters as an input to another function executing the 'integral' function. (this is a test prior to adding more functionality. In this example, you could just use the integral function directly).
If I call the input function, it executes correctly, but when I pass the input function to the function containing the integral command, it throws an error "not enough input arguments". Assuming I am failing to understand a variable scope or function handle concept, thanks for any help!
%passing_function_as_input
ft1(2) %Test call of input function ft1 (works)
[a0] = fscoeff(ft1) %Test call of function using ft1 as input (this line throws error)
function [yt] = ft1(t)
%% Simple Cosine function
A = 1; %(-)Amplitude, unitless without physical context
f = 1/(2*pi); %(Hz) Frequency
C = 0; %(sec)Phase shift
D = 0; %(-)Vertical shift, same units as amplitude
yt = A*cos(2*pi*f*(t+C))+D;
end
function [a0] = fscoeff(ft)
%% Take input function, integrate
lli=0; %Set Lower Limit of Integration
uli=2*pi; %Set Upper Limit of Integration
a0=1/pi*integral(ft,lli,uli);
end
Red error text:
Not enough input arguments.
Error in passing_function_as_input>ft1 (line 12)
yt = A*cos(2*pi*f*(t+C))+D;
Error in passing_function_as_input (line 4)
[a0] = fscoeff(ft1) %Test call of function using ft1 as input

댓글을 달려면 로그인하십시오.

채택된 답변

Rik 2021년 7월 25일
You need to pass a function handle. Probably the line below will do the trick.
fscoeff(@ft1)
The way you wrote it, you actually called the function, instead of passing it as an argument.
댓글 수: 1표시숨기기 없음
Collin Schmidt 2021년 7월 25일
That works! and thank you for the explanation, I was missing the distinction between evaluating the function and passing it.

댓글을 달려면 로그인하십시오.

추가 답변(1개)

dpb 2021년 7월 25일
a0] = fscoeff(ft1)
The above, indeed, is calling ft1 without any arguments and it expects, nay! - requires one.
MATLAB evaluates the argument and passes the result; you would have to pass (and fscoeff would have to expect) a function handle for it to evaluate ft1 internally. But, then, of course, ft1 will always return the same thing so there's no point in not just calling ft1 directly.
What, again, is the idea here???

댓글을 달려면 로그인하십시오.

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by