Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does MATLAB support "callable" (i.e. function-like) classes?

Is it possible to define a MATLAB class such that the objects from this class can be called like any other function?

IOW, I'm asking whether one can write in MATLAB the equivalent of something like the following Python class:

# define the class FxnClass
class FxnClass(object):
    def __init__(self, template):
        self.template = template

    def __call__(self, x, y, z):
        print self.template % locals()

# create an instance of FxnClass
f = FxnClass('x is %(x)r; y is %(y)r; z is %(z)r')

# call the instance of FxnClass
f(3, 'two', False)

...
[OUTPUT]
x is 3; y is 'two'; z is False

Thanks!

like image 313
kjo Avatar asked Dec 08 '22 21:12

kjo


1 Answers

I do not know, whether MATLAB directly supports what you want, but MATLAB does support first-class functions; closures might therefore provide a useable substitute, for instance:

function f = count_call(msg)
    calls = 0;

    function current_count()
        disp(strcat(msg, num2str(calls)));
        calls = calls + 1;
    end

    f = @current_count;
end

In this case, current_count closes over calls (and msg). That way you can express functions that depend on some internal state. You would use it this way:

g = count_call('number of calls: ') % returns a new function ("__init__")
g()                                 % "__call__"
like image 120
Frank Avatar answered Feb 04 '23 22:02

Frank