Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing functions as arguments in Matlab

I'm trying to write a function that is gets two arrays and the name of another function as arguments.

e.g.

main.m:      x=[0 0.2 0.4 0.6 0.8 1.0];     y=[0 0.2 0.4 0.6 0.8 1.0];      func2(x,y,'func2eq')  func 2.m :     function t =func2(x, y, z, 'func')   //"unexpected matlab expression" error message here         t= func(x,y,z);  func2eq.m:       function z= func2eq(x,y)      z= x + sin(pi * x)* exp(y); 

Matlab tells gives me the above error message. I've never passed a function name as an argument before. Where am I going wrong?

like image 232
Meir Avatar asked Apr 28 '10 13:04

Meir


People also ask

Can you pass a function as an argument?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions.

How do you give a function as an input to another function in MATLAB?

You can use function handles as input arguments to other functions, which are called function functions . These functions evaluate mathematical expressions over a range of values. Typical function functions include integral , quad2d , fzero , and fminbnd .

What is function argument in MATLAB?

An argument default value can be any constant or expression that satisfies the size, class, and validation function requirements. Specifying a default value in an argument declaration makes the argument optional. MATLAB uses the default value when the argument is not included in the function call.


1 Answers

You could also use function handles rather than strings, like so:

main.m:

... func2(x, y, @func2eq); % The "@" operator creates a "function handle" 

This simplifies func2.m:

function t = func2(x, y, fcnHandle)     t = fcnHandle(x, y); end 

For more info, see the documentation on function handles

like image 50
Edric Avatar answered Sep 21 '22 21:09

Edric