How to call MATLAB functions from the Linux command line?

前端 未结 8 853
一整个雨季
一整个雨季 2020-12-12 14:46

Basically I have an m file which looks like

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


        
相关标签:
8条回答
  • 2020-12-12 14:57

    You can call functions like this:

    matlab -r "yourFunction(0)"

    0 讨论(0)
  • 2020-12-12 15:01

    I have modified Alex Cohen's answer for my own needs, so here it is.

    My requirements were that the batcher script could handle string and integer/double inputs, and that Matlab should run from the directory from which the batcher script was called.

    #!/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
    

    This script can be called like (if it is on your path): matlab_batcher.sh functionName stringArg1 stringArg2 1 2.0

    Where, the final two arguments will be passed as numbers and the first two as strings.

    0 讨论(0)
  • 2020-12-12 15:04

    MATLAB can run scripts, but not functions from the command line. This is what I do:

    File 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
    

    Call it by entering:

    ./matlab_batcher.sh myfunction myinput
    
    0 讨论(0)
  • 2020-12-12 15:07

    Use:

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

    Make sure matlabCommand has an exit as its last line.

    0 讨论(0)
  • 2020-12-12 15:08
    nohup matlab -nodisplay -nodesktop -nojvm -nosplash -r script.m > output &
    
    0 讨论(0)
  • 2020-12-12 15:12

    Here's a simple solution that I found.

    I have a function func(var) that I wanted to run from a shell script and pass it the first argument for var. I put this in my shell script:

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

    That worked like a treat for me. The trick is that you have to use double quotes with the "-r" command for MATLAB and use single quotes in order to pass the bash argument to MATLAB.

    Just make sure that the last line of your MATLAB script is "exit" or that you run

    matlab -nodesktop -nosplash -r "func('$1'); exit"
    
    0 讨论(0)
提交回复
热议问题