【问题标题】:Is it possible to run matlab function with several command line arguments?是否可以使用多个命令行参数运行 matlab 函数?
【发布时间】:2020-03-03 20:27:28
【问题描述】:

我想编写一个在 matlab 中运行多个测试的脚本。 首先我运行:

TestsPath=$(find . -path "Tests")

返回:

a/b/Tests/ b/c/Tests/ c/d/Tests/

然后我尝试启动 matlab 并传递这些(现在只打印它们)

matlab -nosplash -nodesktop -r "run(RunAllTests(${TestsPath}));"

我的 matlab 函数如下所示:

function [] = RunAllTests(varargin)
    for i=1:nargin
        disp(varargin{i});
    end
end  

但是这个

  run(a/b/Tests
  |

Error: This statement is incomplete.

所以它似乎在涉及第一个空白时会中断。

可以这样做吗?

【问题讨论】:

  • 如果不能一一传递路径,为什么不在 bash 中循环遍历它们呢?只需为对 MATLAB 的调用编写一个包装器,它会遍历找到的所有测试目录。
  • 但是我需要为每个测试用例重新打开 matlab。因为我不能(在 bash 脚本中)启动 matlab,然后不断地将东西传递给它。对吗?
  • 或者,如果答案有效,请编写一个 bash 包装器,将撇号和逗号插入您的 TestPath 字符串并传递它。由于它在空格上中断,我认为您不能在 MATLAB 中执行此操作?因此将带有空格的字符串传递给函数,然后执行strplit 并使用分隔的参数

标签: bash matlab scripting command-line-arguments


【解决方案1】:

如果您的路径中没有任何空格,则以下内容应该有效:

matlab -nosplash -nodesktop -r "RunAllTests ${TestsPath}"

使用您的示例,它与在 Matlab 中运行以下命令相同:

RunAllTests a/b/Tests/ b/c/Tests/ c/d/Tests/

这会在您的函数中产生varargin = {'a/b/Tests/', 'b/c/Tests/', 'c/d/Tests/'}。以这种方式传递给函数的每个参数都被视为字符数组。

【讨论】:

  • 我一开始就是这样运行它的。并且不起作用。
【解决方案2】:

是的,函数参数之间需要逗号,将它们括在单引号中,以便 matlab 将它们视为字符串,并且不需要运行。

TestsPath="'a/b/Tests/', 'b/c/Tests/', 'c/d/Tests/'"
matlab -nosplash -nodesktop -r "RunAllTests(${TestsPath})"

如果您不想在参数之间添加逗号,您可以将 TestsPath 作为单个字符串传递,然后在 matlab 中将其拆分为多个参数。

TestsPath="'a/b/Tests/ b/c/Tests/ c/d/Tests/'"
matlab -nosplash -nodesktop -r "RunAllTests(strsplit(${TestsPath}))"

【讨论】:

    【解决方案3】:

    您可以使用find-printf 操作确保文件名用引号括起来:

    TestsPath=$(find . -path "Tests" -printf "'%p' ")
    

    这将返回

    'a/b/Tests/' 'b/c/Tests/' 'c/d/Tests/' 
    

    可以按照Alex 的建议替换为 MATLAB command syntax 函数调用:

    matlab -nosplash -nodesktop -r "RunAllTests ${TestsPath};"
    

    请注意,如果目录名称中有空格,则需要这些引号。


    请注意,自 MATLAB R2019b 起,-r 已被弃用,取而代之的是新的 -batch 命令行选项:

    matlab -batch "RunAllTests ${TestsPath};"
    

    这在所有平台(包括 Windows!)上都同样有效。

    【讨论】:

    • 在字符串末尾添加"'%p'," 一个额外的,。这还好吗?
    • @FelixRosén:你是对的!我已经编辑了答案以完全删除逗号,并使用 Alex 的建议,即使用命令语法而不是函数语法。
    猜你喜欢
    • 2012-06-30
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多