繁体   English   中英

如何从Linux命令行调用MATLAB函数?

[英]How to call MATLAB functions from the Linux command line?

基本上我有一个m文件,看起来像

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

我只是想从命令行执行它而不进入MATLAB。 我尝试了几个选项( -nodisplay-nodesktop-nojvm-r等),但都没有。 我最终进入MATLAB并且必须输入“quit”退出。

解决办法是什么?

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

使用:

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

确保matlabCommand的出口为最后一行。

你可以调用这样的函数:

matlab -r“yourFunction(0)”

这是我找到的一个简单的解决方案。

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

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

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

只需确保MATLAB脚本的最后一行是“退出”或运行

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

您可以通过将命令传递给Matlab从命令行运行任意函数,如下所示:

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

这将执行Matlab命令funcname('arg1', 'arg2', 'arg3', 'argN') 因此,所有参数都将作为字符串传递,并且您的函数需要处理此问题,但同样,这也适用于任何其他语言的命令行选项。

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

您可以将myfile编译为独立程序并运行它。 使用Matlab的编译器mcc (如果有的话),在这个问题中提供了更多信息。

这个答案是从我对另一个问题的回答中复制的。

我根据自己的需要修改了Alex Cohen的答案,所以现在就是这样。

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

#!/bin/bash

matlab_exec=matlab

#Remove the first two arguments
i=0
for var in "$@"
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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM