How can I pass input parameters when running MATLAB in batch mode in Windows?

408 views (last 30 days)
I want to be able to pass input arguments to the MATLAB file that I want executed when starting MATLAB.
When I execute the following at the Windows command prompt:
matlab -r bench 2
The input argument "2" is ignored by MATLAB.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 21 Nov 2011
There are different approaches to passing input arguments as shown below; use the method that is most appropriate for your application.
1. Define your input parameters before executing the script.
When you use the following syntax:
matlab /r myscript
it is equivalent to opening MATLAB and typing "myscript" at the MATLAB prompt. You can define your input parameters after the "/r" switch, effectively passing input parameters to your script.
As an example, suppose you have the following command stored in a script file:
y = sqrt(x)
You can pass the value for x when running MATLAB in batch mode by typing the following at the DOS prompt:
matlab /r "x=2;myscript"
This will first define x as 2 and then "myscript" is called with x already defined.
2. Convert your script file to a function. Input parameters can then be passed into the function.
As an example, suppose you have the script file below:
y = sqrt(x)
You would like to execute this script in batch mode using different values for x. First you need to convert the script to a function as follows:
function y = myfunc(x)
y = sqrt(x);
You can call this function in batch mode by typing the following at a DOS prompt:
matlab /r "myfunc(2)"
This will call the function "myfunc" passing the input parameter 2 to the function.
3. Store your input parameters in a file that the MATLAB script can open.
For example, if you had previously stored values in a MAT-file, you can open the variables in the script by using the following line of code:
load filename
where 'filename' specifies the path location of the MAT-file. In addition, you could use any of the MATLAB File I/O functions to retrieve input parameters. Your choice of function would depend upon the format of the data.
Note that all scripts and functions called when running MATLAB in batch mode must be on the MATLAB search path. Also, in order to run MATLAB so that it is minimized and does not display the splash screen, you need to include the /nodesktop, /nosplash, and /minimize tags. For example:
matlab /minimize /nosplash /nodesktop /r myfunc(2)
For information on how to pass input parameters when running MATLAB in batch mode in UNIX, see the Related Solution.

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!