MATLAB Answers

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

2 views (last 30 days)
Collin Schmidt
Collin Schmidt on 25 Jul 2021
Commented: Collin Schmidt on 25 Jul 2021
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

Accepted Answer

Rik
Rik on 25 Jul 2021
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 Comment
Collin Schmidt
Collin Schmidt on 25 Jul 2021
That works! and thank you for the explanation, I was missing the distinction between evaluating the function and passing it.

Sign in to comment.

More Answers (1)

dpb
dpb on 25 Jul 2021
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???

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by