MATLAB是否支持"可调用"(即类似函数)类?

kjo*_*kjo 4 oop matlab functional-programming operator-overloading

是否可以定义一个MATLAB类,以便可以像调用任何其他函数一样调用此类中的对象?

IOW,我问的是,是否可以在MATLAB中编写类似以下Python类的内容:

# 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
Run Code Online (Sandbox Code Playgroud)

谢谢!

Fra*_*ank 5

我不知道,MATLAB是否直接支持你想要的东西,但MATLAB确实支持一流的功能; 因此,闭包可以提供可用的替代品,例如:

function f = count_call(msg)
    calls = 0;

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

    f = @current_count;
end
Run Code Online (Sandbox Code Playgroud)

在这种情况下,current_count关闭calls(和msg).这样你就可以表达依赖于某种内部状态的函数.你会这样使用它:

g = count_call('number of calls: ') % returns a new function ("__init__")
g()                                 % "__call__"
Run Code Online (Sandbox Code Playgroud)


Sal*_*ain 4

我有兴趣看看这是否可能,而无需简单地在 Matlab 中创建 java 方法。我知道你可以执行以下操作

classdef ExampleObject
    properties
        test;
    end
    methods
        function exampleObject = ExampleObject(inputTest)
            exampleObject.test=inputTest;
        end
        function f(exampleObject,funcInput)
            disp(funcInput+exampleObject.test);
        end
    end
end

>> e=ExampleObject(5);
>> f(e,10)
    15
Run Code Online (Sandbox Code Playgroud)

但据我所知,如果您尝试重写 call 函数,您会遇到与 Matlab 的括号下标引用冲突subsref您可以在此处找到一个参考,显示如何覆盖它,并且您也许能够让它执行您想要的操作......但这样做似乎不是一个好的形式。不确定 Matlab 如何处理对对象(而不是函数)的调用而不与此混淆。