Matlab 的新函数参数验证是否允许不匹配的名称-值参数?

Does Matlab's new function argument validation allow for unmatched name-value arguments?

Tl; Dr:有没有办法在 Matlab 的新(2019b)函数参数验证中拥有不匹配的可选名称-值参数?

我现有的 Matlab 代码使用输入解析器将可选参数分派到我的 sim 卡。 设置 sim 后,您可以选择一些函数来指示您的对象在其环境中的行为方式,然后调用 runSim。在这个假想的例子中,我的 sim 被定义了两个函数,这两个函数接受唯一和常见的可选输入。

runSim('sharedArg', sa, 'func1Arg1', f1a1, 'func1Arg1', f1a2, 'func2Arg1', f2a1)

runSim 将调用您选择的适当函数来定义您的 sim,并将这些可选参数传递给每个函数。在这种情况下,func1 中的输入解析器将忽略 func2arg1func2 中的输入解析器将忽略 func1Arg1func1Arg2.

一切正常,但我的 sim 将三分之一的时间用于输入解析,因为这些函数在循环中被调用了数千次。并且 Matlab 的输入解析器有一个记录在案的缓慢的历史(在这里插入亵渎)。

最近更新到 2020a,我发现 function argument validation,它比输入解析器可怕得多。在一些功能上对其进行了测试后,不仅代码更具可读性,而且我看到了性能的巨大提升。

function output = func1FirstTry(options)
    % This function does some things
    arguments
        options.sharedArg
        options.func1Arg1 double = 1
        options.func1Arg2 double = 2
    end
    output = 2;
end

喜欢。伟大的。惊人的。但是...

...新函数验证不允许不匹配的参数(或者至少链接页面没有解释它,我还没有找到任何更详尽的文档)。以前,func1 只需要知道它的可选参数。如果我指定 func2arg1 作为 func1 的输入,它会忽略它。使用新函数验证时,这将引发错误,因为我没有在参数块中将 func2Arg1 定义为允许的输入。因此,当我进行此测试时,我不得不改为执行以下操作:

function output = func1SecondTry(options)
    % This function does some things
    arguments
        options.sharedArg
        options.func1Arg1 double = 1
        options.func1Arg2 double = 2
        options.func2Arg1 double = Nan
    end
    % Rest of the code goes here
end

现在可以了,但我还必须更改 func2 以接受 func1 的可选参数。我还有 20 多个带有可选参数的函数需要考虑,所以显然这个策略不会奏效。有没有一种方法可以指定我想以与输入解析器相同的方式接受和忽略任何未命名的可选输入?具体来说,我希望 func1FirstTry('func2Arg1', 3) 不会出错,而不会将 func2Arg1 添加到参数块中。

这最终不是我采用的解决方案,但我认为一个可能的答案是定义一个虚拟 class,将解析器的所有可能输入作为 public 属性,然后使用values from class properties syntax。因此 class 的所有属性都是函数的合法输入,但是您只能访问特定于该函数的参数。如果您想更改默认值,此语法还允许您重新定义任何特定参数。

% Define this in its own file
classdef OptionalArgumentClass
    properties
        sharedArg
        func1Arg1
        func1Arg2
        func2Arg1
        argumentUndefinedByOtherFunctions
    end
end
% In a separate file from class
function output = func1(options)
    % This function does some things
    arguments
        options.?Path.To.OptionalArgumentClass
        options.func1Arg1 = 1 % Can choose specific default values here if needed
    end

    % options.func1Arg2 has no default value, so this will error if unspecified
    output = options.func1Arg1 + options.func1Arg2;
end

包含 options.?Path.To.OptionalArgumentClass 意味着我可以指定 func2Arg1argumentUndefinedByOtherFunctions 并优雅地忽略它们,这就是我一直在寻找的。