MATLAB Answers

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

2 ビュー (過去 30 日間)
Collin Schmidt
Collin Schmidt 2021 年 7 月 25 日
コメント済み: Collin Schmidt 2021 年 7 月 25 日
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!
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;
function [a0] = fscoeff(ft)
%% Take input function, integrate
lli=0; %Set Lower Limit of Integration
uli=2*pi; %Set Upper Limit of Integration
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.
The way you wrote it, you actually called the function, instead of passing it as an argument.
  1 件のコメント
Collin Schmidt
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???




Community Treasure Hunt

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

Start Hunting!

Translated by