jxramos
jxramos

Reputation: 8266

Does Matlab support function-objects?

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?

Upvotes: 2

Views: 224

Answers (1)

Bas Swinckels
Bas Swinckels

Reputation: 18488

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

Upvotes: 4

Related Questions