13

I have a matlab file that takes in a file. I would like to run that program in the matlab shell, such as prog. I need to implement it so that it takes a number of arguments, such as "prog filename.txt 1 2 which would mean that i can use filename.txt and 1 2 as variables in my program.

Thank you!

bubbles
  • 861
  • 4
  • 13
  • 30
  • 2
    What have you tried? What do you have so far? Edit your question with the answers. – mathematical.coffee Jan 24 '12 at 02:53
  • 1
    possible duplicate of [How can i pass command line arguments to a standalone MATLAB executable running on linux/unix?](http://stackoverflow.com/questions/3335505/how-can-i-pass-command-line-arguments-to-a-standalone-matlab-executable-running) – gnovice Jan 24 '12 at 15:22

2 Answers2

26

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). It's 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 it's located at the Matlab working path, otherwise it'll not be able to recognize your script.

Finally, to execute the script you use

matlab -r "prog arg1 arg2"

which is equivalent to calling

prog(arg1,arg2)

from inside Matlab.

*- tested in Windows and Linux environments

SIMEL
  • 8,745
  • 28
  • 84
  • 130
  • 1
    I wonder whether we can write a script (say, saved as `script.m`) behaving like `load` for example, so that we call it in MATLAB console with `script arg`. – Ziyuan Dec 09 '16 at 13:58
  • I tried this today on matlab R2017B on windows and it did not work. The error was "Error on (line ) – pnkjmndhl Nov 20 '18 at 19:03
1

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 doesn't 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 / %s\n',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
try
    prog(1, 'file.txt')
catch me
% On error, print error message and exit with failure
    fprintf('%s / %s\n',me.identifier,me.message)
    exit(1)
end
% Else, exit with success
exit(0)