Running a matlab program with arguments

Running a matlab program with arguments

In order to make a script accept arguments from the command line, you must first turn it into a function that will get the arguments you want, i.e if your script is named prog.m, put as the first line

function []=prog(arg1, arg2)

and add an end at the end (assuming that the file has only one function). Its very important that you call the function the same name as the file.

The next thing is that you need to make sure that the script file is located at the same place from where you call the script, or its located at the Matlab working path, otherwise itll not be able to recognize your script.

Finally, to execute the script you use

matlab -r prog arg1 arg2

which is equivalent to calling


from inside Matlab.

*- tested in Windows and Linux environments

Once your function is written in a separate file, as discussed by the other answer you can call it with a slightly more complicated setup to make it easier to catch errors etc.

There is useful advice in this thread about ensuring that Matlab doesnt launch the graphical interface and quits after finishing the script, and reports the error nicely if there is one.

For example:

matlab -nodisplay -nosplash -r try, prog(1, file.txt), catch me, fprintf(%s / %sn,me.identifier,me.message), exit(1), end, exit(0)

The script given to Matlab would read as follows if line spaces were added:

% Try running the script
    prog(1, file.txt)
catch me
% On error, print error message and exit with failure
    fprintf(%s / %sn,me.identifier,me.message)
% Else, exit with success

Running a matlab program with arguments

Leave a Reply

Your email address will not be published.