matlab - 'varargin' 函数在仅提供名称-值对时给出错误 : MATLAB

标签 matlab function parsing

我正在尝试构建我自己版本的 MATLAB 的 dir 函数。我当前的代码(如下)几乎可以工作,但我在解析特定的输入组合时遇到问题。

我希望它做的是:

  • 不要列出隐藏的文件夹。
  • 有一个 bool 参数(默认为 false)以仅返回目录名称而不返回文件。
  • 文件夹路径有一个可选字段(默认为当前目录)。

为了更清楚,我想创建可以处理这些组合的函数 dir2:

  1. dir2 这应该列出当前目录中所有未隐藏的文件或文件夹
  2. dir2('path_to_directory') 这应该列出指定目录中的每个非隐藏文件或文件夹
  3. dir2('OnlyDirectories', true) 这应该只列出当前目录中的非隐藏文件夹
  4. dir2('path_to_directory', 'OnlyDirectories', true) 这应该只列出指定目录中的非隐藏文件夹

我当前的版本是这样的:

function list = dir2(varargin)
    p = inputParser;

    addOptional(p, 'name', '.', @ischar);
    addParameter(p, 'OnlyDirectories', false, @islogical);
    parse(p, varargin{:});

    list = dir(p.Results.name);
    if p.Results.OnlyDirectories
        dirFlags = [list.isdir];
        list = list(dirFlags); % Keeping only directories
    end
    % Deleting hidden folders from the list
    list = list(arrayfun(@(x) ~strcmp(x.name(1),'.'), list)); 
end

这适用于情况 124 但不适用于情况 3 .在这种情况下,它给了我错误:

Expected a string scalar or character vector for the parameter name, instead the input type was 'logical'.

我想我可能遗漏了一些关于 MATLAB 的输入解析的微不足道的东西,但我不知道是什么。

最佳答案

你是对的,解析器似乎给出了一些奇怪的结果,一个相关的问题可能是 this one .

一种适用于当前形式的函数的解决方法是添加检查是否给出了 2 个输入。如果有 2 个输入,假设它是您的 OnlyDirectories 标志并使用默认的 name 值。代码看起来像这样并通过了所有 4 个示例用例。

function list = dir2(varargin)
    p = inputParser;
    addOptional(p, 'name', '.', @ischar);
    addParameter(p, 'OnlyDirectories', false, @islogical);
    if numel(varargin) == 2 
        varargin = [{'.'}, varargin]; 
    end
    parse(p, varargin{:});
    list = dir(p.Results.name);
    if p.Results.OnlyDirectories
        dirFlags = [list.isdir];
        list = list(dirFlags); 
    end
    list = list(arrayfun(@(x) ~strcmp(x.name(1),'.'), list)); 
end

虽然有点老套,但有可能给出令人困惑的错误消息。最好将两个输入都作为名称-值对

function list = dir2(varargin)
    p = inputParser;
    addParameter(p, 'name', '.', @ischar);
    addParameter(p, 'OnlyDirectories', false, @islogical);
    % ... other code
end

使用:dir2('name', 'C:/Folder/MyStuff/', 'OnlyDirectories', true)

关于matlab - 'varargin' 函数在仅提供名称-值对时给出错误 : MATLAB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45670058/

相关文章:

matlab - 如何在 MATLAB 中获取像素邻居?

python - 如何使用 Python 正则表达式来匹配 MATLAB 的函数语法?

javascript - jQuery AJAX 调用 PHP 类函数

c++ - 虚函数表偏移量

c++ - boost::spirit char/string 混合

Char 数组到数学方程

class - 如何检查值是否是 Matlab 中的有效属性?

c - 函数在独立模式下工作正常,但在较大的程序中则不行

c - Bison:$ 变量($1 $2 等)如何与非 token 一起使用?

python - 为什么 matplotlib(python)中的 cohere 函数给出的答案与 MATLAB 中的 mscohere 函数不同?