【问题标题】:How to get function arguments matlab [duplicate]如何获取函数参数matlab [重复]
【发布时间】:2012-10-05 11:52:21
【问题描述】:

可能重复:
How do I retrieve the names of function parameters in matlab?

我正在寻找一种方法来获取传递给或期望我的函数的所有参数。 args() 命令似乎很理想,但仅适用于过程。有没有办法做到这一点。

我想这样做的原因是我可以检查更少的行。即通过编写一项检查然后对所有参数执行来检查所有输入是否为数字。因此,如果有好的替代方案,我愿意接受。

谢谢

【问题讨论】:

    标签: matlab


    【解决方案1】:

    您可以使用varargin,正如 petrichor 所提到的。 varargin 是一个单元格,因此您可以使用 cellfun 在一行中轻松验证所有参数:

    function c = test(varargin)
    cellfun(@(arg)validateattributes(arg, {'numeric'}, {'integer'}), varargin);
    

    以上代码对所有函数参数运行validateattributes。另一方面,如果你想要命名变量,你仍然可以将它们分组到单元格中并像上面那样运行特定的测试:

    function c = test(i1, i2, d1, d2)
    
    % validate integer arguments
    cellfun(@(arg)validateattributes(arg, {'numeric'}, {'integer'}), {i1, i2});
    
    % validate double arguments
    cellfun(@(arg)validateattributes(arg, {'double'}, {'positive'}), {d1, d2});
    

    【讨论】:

      【解决方案2】:

      您正在寻找的是varargin,它使您能够处理可变数量的输入参数。

      【讨论】:

      • 我实际上并不想要可变数量的参数。并且对于大多数代码都希望使用命名变量以使其更清晰。我只是想要一种无需重复代码即可完成断言的方法。
      猜你喜欢
      • 2019-07-31
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多