我想在 bash 中以非交互方式调用 matlab,并在 Matlab 之外使用其结果。
例如我有一个脚本test.m
rand(3,4)
quit
当我在 bash 中执行时
$ matlab -nosplash -nodesktop -nodisplay -r test
Warning: No window system found. Java option 'MWT' ignored
< M A T L A B (R) >
Copyright 1984-2008 The MathWorks, Inc.
Version 7.7.0.471 (R2008b)
September 17, 2008
To get started, type one of these: helpwin, helpdesk, or demo.
For product information, visit www.mathworks.com.
ans =
0.8147 0.9134 0.2785 0.9649
0.9058 0.6324 0.5469 0.1576
0.1270 0.0975 0.9575 0.9706
是否可以抑制Matlab的启动消息,只显示结果,也不显示“ans=”。
注意我问的是一个一般性问题,不仅仅是针对这个例子。
感谢和问候!
尝试使用 -logfile 命令行选项:
-logfile log - Make a copy of any output to the command window in file log. This includes all crash reports.
然后您可以使用任何您想要的方式轻松删除前几行(例如 sed)。示例:
matlab.exe -nosplash -nodesktop -nojvm -logfile out.log -r 'rand(3,3), exit'
sed '1,5d' out.log
此外,如果您正在从脚本运行,需要它在继续之前完成运行,请使用 -wait 选项:
-wait - MATLAB is started by a separate starter program
which normally launches MATLAB and then immediately
quits. Using the -wait option tells the starter
program not to quit until MATLAB has terminated.
This option is useful when you need to process the
the results from MATLAB in a script. The call to
MATLAB with this option will block the script from
continuing until the results are generated.
有关 MATLAB 启动选项的更多信息可以在 here 或在
matlab
可执行参考页中找到:Windows/Unix
您可以使用 Unix 命令“tail +n”删除前 n 行输出。该标头看起来有 10 行,因此这将删除它。
$ matlab -nosplash -nodesktop -nodisplay -r test | tail +10
但这有点脆弱,因为警告(如“无窗口系统”)将被删除,并且标头大小将根据发生的警告而变化(这些警告是有用的诊断)。另外,该警告可能位于 STDERR 而不是 STDOUT 上,因此“tail +9”可能就是您所需要的。
更可靠的方法可能是修改 Matlab 脚本以使用 fopen/fprintf/fclose 写入单独的文件。这样,Matlab 中的标头、警告、错误等就会与您想要的格式化输出分开。要使“disp”输出转到该单独的文件句柄,您可以使用 evalc 捕获它。可以使用 -r 消息中的 test() 参数来指定输出文件,并将 $$ env 变量(bash 进程的 PID)合并到文件名中以防止多进程环境中的冲突。
function test(ppid)
outfile = sprintf('outfile-%d.tmp', ppid);
fh = fopen(outfile, 'w');
myvar = rand(3,4);
str = evalc('disp(myvar)');
fprintf(fh, '%s', str);
fclose(fh);
要从 bash 调用它,请使用此调用形式。 (这里可能有一些小语法问题;我现在没有 Unix 机器可以测试。)
% matlab -nosplash -nodisplay -r "test($$)" -logfile matlab-log-$$.tmp
假设您的 bash PID 是 1234。现在您已在 outfile-1234.tmp 中获得输出,并在 matlab-log-1234.tmp 中获得 Matlab 日志。如果您不想依赖 pwd,请将它们放在 /tmp 中。您可以扩展它以从单个 matlab 调用创建多个输出文件,如果您需要计算多个事物,则可以节省启动成本。
我建议将输出保存到文件中,然后读取该文件。这种方法稍微复杂一些,但随着格式变化等的变化,不那么脆弱。它给你更多的控制权。您会在网络上找到大量脚本来将 Matlab 文件转换为不同的宿主语言。
示例:
A = randn(3, 2);
save temp_output.mat A
# Later, read temp_output.mat in whichever language you desire.
像这样调用 MATLAB
matlab -nodisplay <test.m &>matlab.output
会将所有启动消息和其他显示的输出转储到 matlab.output 文件中(可以将其命名为您想要的任何名称)。如果您然后(按照彼得的建议)让 test.m 将您需要的结果保存到文件中,使用
csvwrite('temp_output.txt',A)
或其他适当的输出函数,您可以在该文件中读取并继续。
使用 -batch 选项而不是 -r 将抑制启动消息。