|
| 1 | +#!/bin/sh |
| 2 | +# Executes a specified MATLAB command in batch mode. With MATLAB R2018b+, |
| 3 | +# running this script is equivalent to executing "matlab -batch command" from |
| 4 | +# the system prompt. |
| 5 | +# |
| 6 | +# Copyright 2020 The MathWorks, Inc. |
| 7 | + |
| 8 | +usage() { |
| 9 | + echo '' |
| 10 | + echo ' Usage: run_matlab_command.sh command' |
| 11 | + echo '' |
| 12 | + echo ' command - MATLAB script, statement, or function to execute.' |
| 13 | + echo '' |
| 14 | +} |
| 15 | + |
| 16 | +ver_less_than() { |
| 17 | + [ "$(ver_str "$1")" -lt "$(ver_str "$2")" ] |
| 18 | +} |
| 19 | + |
| 20 | +ver_str() { |
| 21 | + echo "$@" | awk -F. '{ printf("%d%03d%03d%09d\n", $1,$2,$3,$4); }'; |
| 22 | +} |
| 23 | + |
| 24 | +command=$1 |
| 25 | +if [ -z "$command" ]; then |
| 26 | + usage |
| 27 | + exit 1 |
| 28 | +fi |
| 29 | + |
| 30 | +if ! matlab_path="$(command -v matlab)" || [ -z "$matlab_path" ]; then |
| 31 | + echo "'matlab'"' command not found. Please make sure MATLAB_ROOT/bin is on' |
| 32 | + echo 'the system path, where MATLAB_ROOT is the full path to your MATLAB' |
| 33 | + echo 'installation directory.' |
| 34 | + exit 1 |
| 35 | +fi |
| 36 | + |
| 37 | +# resolve symlink to target |
| 38 | +while [ -h "$matlab_path" ]; do |
| 39 | + dir=$(dirname -- "$matlab_path") |
| 40 | + target=$(readlink "$matlab_path") |
| 41 | + matlab_path=$(cd "$dir" && cd "$(dirname -- "$target")" && pwd)/$(basename -- "$target") |
| 42 | +done |
| 43 | + |
| 44 | +matlab_root=$(dirname -- "$(dirname -- "$matlab_path")") |
| 45 | + |
| 46 | +# try to discover the MATLAB version |
| 47 | +if [ -f "$matlab_root"/VersionInfo.xml ]; then |
| 48 | + # get version tag contents |
| 49 | + matlab_ver=$(sed -n 's:.*<version>\(.*\)</version>.*:\1:p' < "$matlab_root"/VersionInfo.xml) |
| 50 | +elif [ -f "$matlab_root"/toolbox/matlab/general/Contents.m ]; then |
| 51 | + # get version printed after "MATLAB Version" |
| 52 | + matlab_ver=$(grep -o 'MATLAB Version .*' < "$matlab_root"/toolbox/matlab/general/Contents.m | awk -v N=3 '{print $N}') |
| 53 | +fi |
| 54 | + |
| 55 | +# if version not discovered, assume worst-case version of 0 |
| 56 | +matlab_ver=${matlab_ver:-0} |
| 57 | + |
| 58 | +# use -r to launch MATLAB versions below R2018b (i.e. 9.5), otherwise use -batch |
| 59 | +if ver_less_than "$matlab_ver" '9.5'; then |
| 60 | + # define start-up options |
| 61 | + opts='-nosplash -nodesktop' |
| 62 | + if ! ver_less_than "$matlab_ver" '8.6'; then |
| 63 | + opts="$opts -noAppIcon" |
| 64 | + fi |
| 65 | + |
| 66 | + # escape single quotes in command |
| 67 | + exp=$(echo "$command" | sed "s/'/''/g") |
| 68 | + |
| 69 | + matlab "$opts" -r "try,eval('$exp'),catch e,disp(getReport(e,'extended')),exit(1),end,exit" |
| 70 | +else |
| 71 | + matlab -batch "$command" |
| 72 | +fi |
0 commit comments