2010-01-04 116 views
30

基本上我有一个m文件,它看起来像如何从Linux命令行调用MATLAB函数?

function Z=myfunc() 
    % Do some calculations 
    dlmwrite('result.out',Z,','); 
end 

我只想没有进入MATLAB在命令行中执行它。我试了几个选项(-nodisplay-nodesktop-nojvm-r等),没有一次成功。我最终进入MATLAB,必须输入“quit”才能退出。

解决方案是什么?

+1

从MathWorks公司:我如何在UNIX机器上在批处理模式下运行MATLAB? ](http://www.mathworks.com/support/solutions/en/data/1-15HNG/index.html) – 2010-01-04 18:24:21

回答

25

MATLAB可以运行脚本,但不能从命令行功能。这是我做的:

文件matlab_batcher.sh

#!/bin/sh 

matlab_exec=matlab 
X="${1}(${2})" 
echo ${X} > matlab_command_${2}.m 
cat matlab_command_${2}.m 
${matlab_exec} -nojvm -nodisplay -nosplash < matlab_command_${2}.m 
rm matlab_command_${2}.m 

叫它输入:

./matlab_batcher.sh myfunction myinput 
+0

这是什么输入? – ablimit 2010-01-04 21:13:27

+0

我做的只是: matlab -nojvm -nodisplay -nosplash /dev/null 2>/dev/null 无论如何,它打印一些错误消息,但结果是正确的。 – ablimit 2010-01-04 21:37:22

+0

是的!有效。 谢谢亚历克斯! – ablimit 2010-01-04 21:49:54

20

用途:

matlab -nosplash -nodesktop -logfile remoteAutocode.log -r matlabCommand 

确保matlabCommand有一个出口作为其最后线。

1
nohup matlab -nodisplay -nodesktop -nojvm -nosplash -r script.m > output & 
+1

为什么'-nojvm'?我可能需要'java'功能。 – gerrit 2013-02-06 09:30:11

12

你可以调用的函数是这样的:

MATLAB -r “yourFunction中(0)”

+0

可以在这些大括号中给出输入吗? – 2013-01-25 15:59:55

+2

如果你不希望MATLAB在运行该函数后继续执行,那么使用''matlab -r'func(arg1,arg2,..);退出“'''。 – nimrodm 2013-06-27 08:42:14

0

你可以编译成myfile一个独立的程序和运行来代替。使用Matlab的编译器mcc为(如果有的话),更多信息在该question提供。

这个答案是从我的答案复制到another question

3

你可以通过一个命令MATLAB,这样运行在命令行的任意函数:

matlab -nodisplay -r "funcname arg1 arg2 arg3 argN" 

这将执行MATLAB命令funcname('arg1', 'arg2', 'arg3', 'argN')。因此,所有的参数都会以字符串形式传递,而你的函数需要处理这个,但是这又一次适用于任何其他语言的命令行选项。

0

我已经修改了亚历克斯·科恩的回答为我自己的需要,所以在这儿呢。

我的要求是批处理脚本可以处理字符串和整数/双输入,并且Matlab应该从调度器脚本被调用的目录运行。

#!/bin/bash 

matlab_exec=matlab 

#Remove the first two arguments 
i=0 
for var in "[email protected]" 
do 
args[$i]=$var 
let i=$i+1 
done 
unset args[0] 

#Construct the Matlab function call 
X="${1}(" 
for arg in ${args[*]} ; do 
    #If the variable is not a number, enclose in quotes 
    if ! [[ "$arg" =~ ^[0-9]+([.][0-9]+)?$ ]] ; then 
    X="${X}'"$arg"'," 
    else 
    X="${X}"$arg"," 
    fi 
done 
X="${X%?}" 
X="${X})" 

echo The MATLAB function call is ${X} 

#Call Matlab 
echo "cd('`pwd`');${X}" > matlab_command.m 
${matlab_exec} -nojvm -nodisplay -nosplash < matlab_command.m 

#Remove the matlab function call 
rm matlab_command.m 

该脚本可以被称为像(如果它是你的路径上): matlab_batcher.sh functionName stringArg1 stringArg2 1 2.0

其中,最后两个参数将作为数字和前两个作为字符串传递。

7

这里有一个简单的解决方案,我发现。

我有一个函数FUNC(VAR),我想从一个shell脚本运行,并传递给它的第一个参数的变种。我把它放在我的shell脚本中:

matlab -nodesktop -nosplash -r "func('$1')" 

这对我来说就像一种享受。诀窍是你必须对MATLAB使用双引号和“-r”命令,并使用单引号将bash参数传递给MATLAB。

只要确保你的MATLAB脚本的最后一行是“退出”,或者你运行

matlab -nodesktop -nosplash -r "func('$1'); exit" 
+0

请注意,至少在我的设置中,在$ 1周围使用单引号将环境变量作为字符串传递,并且使用$ 1左右的任何引号将其作为数字传入。另外,在我的设置中,如果func是一个函数.m文件,则不需要将退出放在双引号中。 – Grittathh 2013-05-23 22:01:53