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 commentaire

"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)
ans = 'blah 8'
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.

Connectez-vous pour commenter.

Réponses (1)

I am not certain what you are doing.
Try this —
anon = @(x) x+3;
y = hello(3,anon)
y = 18
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.
.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by