【问题标题】:Overloading functions重载函数
【发布时间】:2011-12-25 18:27:22
【问题描述】:

有没有办法在 Matlab 的同一个类中拥有两个同名但参数不同的函数?

【问题讨论】:

标签: oop matlab overloading


【解决方案1】:

简而言之:不,这是不可能的。

但是,您可以模仿这种行为:

显然,由于 Matlab 是一种动态语言,您可以传递任何类型的参数并检查它们。

function foo(x)
    if isnumeric(x)
        disp(' Numeric behavior');
    elseif ischar(x)
        disp(' String behavior');
    end
end

你也可以使用varargin,检查参数个数,改变行为

function goo(varargin)
    if nargin == 2
        disp('2 arguments behavior');
    elseif nargin == 3
        disp('3 arguments behavior');   
    end
end

【讨论】:

    【解决方案2】:

    安德烈已经给出了正确答案。但是,我已经进行了一段时间的实验,我想展示我认为另一种相对简单但有一些好处的方法。此外,这是 MATLAB 用于其内置函数的一种方法。

    我指的是这种键值对传递参数的方式:

    x = 0:pi/50:2*pi;
    y = sin(x);
    plot(x, y, 'Color', 'blue', 'MarkerFaceColor', 'green');
    

    解析varargin 元胞数组的方法有很多种,但迄今为止我发现的最简洁的方法是使用 MATLAB inputParser 类。

    例子:

    function makeSandwiches(amount, varargin)
    %// MAKESANDWICHES Make a number of sandwiches.
    %// By default, you get a ham and egg sandwich with butter on white bread.
    %// Options:
    %// amount       : number of sandwiches to make (integer)
    %// 'butter'     : boolean
    %// 'breadType'  : string specifying 'white', 'sourdough', or 'rye'
    %// 'topping'    : string describing everything you like, we have it all!
    
    p = inputParser();                          %// instantiate inputParser
    p.addRequired('amount', @isnumeric);        %// use built-in MATLAB for validation
    p.addOptional('butter', 1, @islogical);
    p.addOptional('breadType', 'white', ...     %// or use your own (anonymous) functions
        @(x) strcmp(x, 'white') || strcmp(x, 'sourdough') || strcmp(x, 'rye'));
    p.addOptional('toppings', 'ham and egg', @(x) ischar(x) || iscell(x))
    p.parse(amount, varargin{:});               %// Upon parsing, the variables are
                                                %// available as p.Results.<var>
    
    %// Get some strings
    if p.Results.amount == 1
        stringAmount = 'one tasty sandwich';
    else
        stringAmount = sprintf('%d tasty sandwiches', p.Results.amount);
    end
    
    if p.Results.butter
        stringButter = 'with butter';
    else
        stringButter = 'without butter';
    end
    
    %// Make the sandwiches
    fprintf(['I made you %s %s from %s bread with %s and taught you ' ...
        'something about input parsing and validation in MATLAB at ' ...
        'the same time!\n'], ...
        stringAmount, stringButter, p.Results.breadType, p.Results.toppings);
    
    end
    

    (在 cmets 后加斜线,因为 SO 不支持 MATLAB 语法高亮显示)

    这种方法的额外好处是:
    - 设置默认值的可能性(如 Python,您可以在函数签名中设置 arg=val
    - 以简单的方式执行输入验证的可能性
    - 您只需要记住选项名称,而不是它们的顺序,因为顺序无关紧要

    缺点:
    - 在执行许多函数调用时可能会有一些开销可能会变得很大(未测试)
    - 您必须使用 inputParser 类中的 Results 属性,而不是直接使用变量

    【讨论】:

      猜你喜欢
      • 2014-06-18
      • 2012-03-09
      • 1970-01-01
      • 2023-03-24
      • 2017-08-06
      • 2018-03-05
      • 2020-03-23
      相关资源
      最近更新 更多