0

Is it possible to define a function with a function handler as an argument in Matlab?

I've tried with

function x = name(@f,gh)

but I get an error message stating Invalid syntax at '@'.

1 Answers1

2

You cannot use syntax involving @ in function definition. The anonymous function handle would do the work:

function x = SO_Example(h,gh)
x = h(gh);

And you can call the function as follows:

SO_Example(@(a)a.^2 , 2)
ans = 4

Or like this:

h = @(a)a.^2;
SO_Example(h,2)

ans = 4

Please, see comments for additional explanations

brainkz
  • 1,335
  • 10
  • 16
  • To clarify, you might add the explanation that the argument parser will try to parse "@()..something" rather than pass a function handle to the function body. – Carl Witthoft Jan 18 '16 at 15:57
  • @CarlWitthoft good point for understanding of mechanisms behind Matlab. But, aside from this, what is the point in passing `@(...)`? Argument is something that is not known exactly prior to the function execution. I think that OP just wanted to tell Matlab that one of arguments is a function. – brainkz Jan 18 '16 at 19:40