Run Matlab script from a shell script – using command line

Suppose you have a matlab script file matlab_func.m inside the directory
matlab_script_directory. Also matlab_func(string_argument,numerical_argument) takes the string_argument in the form ‘some string’ and numerical_argument (like 28, 49.0 etc).

In your bash script, you want to execute matlab_func() with arguments passed from bash script and return to the bash shell for executing further commands following it. Use the following in your bash script

# Create Matlab script file 
temp_mat_script="matlab_script_directory/run_mat_script.m"
string_argument="some string"
numerical_argument="28"
echo "matlab_func('$string_argument',$numerical_argument);" > $temp_mat_script # create new file and write 
echo "exit" >> $temp_mat_script # append to file

# Execute Matlab script file
curr_dir=$PWD
cd matlab_script_directory
matlab -nojvm -nodisplay -nosplash -r run_mat_script 
cd $curr_dir

# Delete temporary file
rm $temp_mat_script

 
Note: Instead of changing directory to matlab_script_directory, you can use
echo "addpath matlab_script_directory" > matlab_script_directory/,
if run_mat_script.m is created in your current directory.

 

Note: If the “matlab” command ( application script file) location is not
included in the PATH variable, then you need to specify as Path_To_Matlab_Command/matlab.Otherwise add it to PATH variable as

export PATH=$PATH:Path_To_Matlab_Command

You can add the above code to ~/.bashrc file, to make it permanent.

Leave a comment