在MATLAB classdef中,你能定义一个“any_function”吗?

时间:2015-07-03 15:35:15

标签: matlab class object methods

在MATLAB的classdef中,你能定义一个执行调用它的 any_function 的方法吗?

例如,假设我在MATLAB中定义了这个自定义类类型:

classdef custfloat

    properties
      value = double(0);   % Double value
    end

    methods


        function obj = custfloat(v, ex, mant)

            obj.value = ........blah blah blah;
        end


        function v = any_function(arg1,arg2)

            v = any_function(arg1.value, arg2.value);
        end

    end
end

因此,只要为两个双打定义了any_function,无论any_function实际是什么,它都会有效。

这有意义吗?

1 个答案:

答案 0 :(得分:1)

我不确定你的问题究竟意味着什么,但我认为你可以得到你正在寻找我的子类double

例如,这是一个简单的类,它扩展double以创建类似double的内容,但也有一个单位(例如米或秒)。< / p>

classdef custDouble < double

    properties

        unit

    end

    methods

        function obj = custDouble(v, u)
            % Do something with exponents and mantissas instead if you like,
            % I can't remember floating point stuff well enough for this
            % example
            obj = obj@double(v);
            obj.unit = u;
        end

        function val = myExtraMethod(obj)

            val = custDouble(obj*2, obj.unit);

        end

    end

end

您现在可以像这样创建custDouble

>>a = custDouble(2, 'm')
a = 
  custDouble with properties:

    unit: 'm'
  double data:
     2

您可以拨打额外的方法:

>> b=a.myExtraMethod
b = 
  custDouble with properties:

    unit: 'm'
  double data:
     4

你可以调用任何适用于双打的常规函数​​:

>> sqrt(a)
ans =
       1.4142

请注意,sqrt这里将返回double,而不是custDouble - 它只会对基础double采取行动。如果您希望常规函数(例如sqrt)返回custDouble,则需要使用custDouble上的方法重载它们,这些方法将以适当的方式运行(例如,例如,在基础builtin('sqrt',...)上调用double,然后构建正确的单位,然后将它们放在custDouble中 - 与上面myExtraMethod的方式相同。

在文档中搜索&#34;子类化MATLAB内置类型&#34;了解更多信息。