Does Matlab support function-objects?

158 views Asked by At

Trying to figure out if I have access to function object programming techniques for use in our Matlab scripts. This would be analogous to .NET's Func type, or Python's function objects. Does Matlab give functions first class object status?

1

There are 1 answers

3
Bas Swinckels On BEST ANSWER

Matlab does have function handles which can be passed to other functions. As one example, the function fzero will find the zero-crossing of the function you give as its first argument. Function handles can be stored in variables, cell-arrays or structs. Matlab also has anonymous functions, which are similar to Python's lambda expressions. So it seems that functions in Matlab have all the properties to be considered first class.

Some random examples:

>> sq = @(x) x^2 - 2
sq = 
    @(x)x^2-2

>> fzero(sq, 1)
ans =
    1.4142

>> class(sq)
ans =
function_handle

>> functions = {@(x) 2 * x, @(y) 3 * y, @exp}
functions = 
    @(x)2*x    @(y)3*y    @exp

>> functions{2}(10)
ans =
    30

>> functions{3}(1)
ans =
    2.7183