Can I use an anonymous function as an input to a regular function
显示 更早的评论
For instance, if I have a function:
function output = hello(input1 ,anon)
and an anonymous function: anon = @() x+3
Can I use the anonymous function as the second input to the hello function, and if so how would I call the hello function in the command window? Because when I try, it says that the variable anon is not defined.
1 个评论
"Can I use the anonymous function as the second input to the hello function"
Of course:
x = 5;
f = @() x+3; % the variable name is irrelevant
hello('blah',f)
function output = hello(input1 ,anon)
output = sprintf('%s %d',input1,anon());
end
"Because when I try, it says that the variable anon is not defined."
Just because the variable name is the same, does not mean that data will jump from the base workspace to the function workspace. It won't: https://www.mathworks.com/help/matlab/matlab_prog/base-and-function-workspaces.html
That is why I used different variable names in the code above, to emphasize that their names are irrelevant.
回答(1 个)
I am not certain what you are doing.
Try this —
anon = @(x) x+3;
y = hello(3,anon)
function y = hello(input1,fcn)
y = input1 .* fcn(input1);
end
The ‘hello’ function can of course be coded as:
function y = hello(input1,anon)
I used ‘fcn’ for the second argument simply to demonstrate that the second argument can be any function.
.
类别
在 帮助中心 和 File Exchange 中查找有关 Descriptive Statistics 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!