Apart from using a wrapper, is there any way to use getopts
-style arguments (e.g., -v
or -n 3
or --some_parameter=7
) in matlab programs compiled using mcc
?
2 Answers
1
It sounds like you are looking for an inputParser object.
edited based on comment about link-only answer.
Here's some example usage for a function which has 2 required inputs & 2 optional parameters:
function hObj = dasImagePrototype(hAx, dasStruct, varargin)
% ...
defaultDepthUnit = getpref('HOTB', 'units_unitSystem', 1);
p = inputParser;
p.addRequired('hAx', @(x) isa(x, 'matlab.graphics.axis.Axes'))
p.addRequired('dasStruct', @(x) isstruct(x) && isfield(x,'psd'))
p.addParameter('depthUnit', defaultDepthUnit, @(x) ismember(x,1:2))
p.addParameter('whichFbe', 1, @(x) floor(x)==x && x>0)
p.parse(hAx, dasStruct, varargin{:})
% access hAx & dasStruct directly since they're `Required` inputs
% but we still pass them to the input parser anyways to validate
hObj.hAx = hAx;
hObj.dasStruct = dasStruct;
% note that since depthUnit & whichFbe are `Parameter` and not
% `Required` inputs, we need to access them from the p object
hObj.depthUnit = p.Results.depthUnit;
hObj.whichFbe = p.Results.whichFbe;
If you want to create
getopt
-like command-line functionality for your MATLAB programs (compiled or not), then using aninputParser
object (typically the best approach to input handling) might not be your best option. TheinputParser
functionality is geared well towards function arguments that follow a specific ordering (i.e. positioning within the argument list) and which follow the "parameter/value pair" format. Typicalgetopt
style functionality involves option lists that are not required to follow a specific ordering and have both "option only" (e.g.-v
) or "option with argument" (e.g.-n 3
or--some_parameter=7
) formats.You'll likely need to add your own input parsing routines at the very beginning of your compiled program. As mentioned here and here, when you use command syntax to call your program, the inputs are all passed as a series of character vectors. If you define a function with a variable input argument list like so:
Then calling the function as follows:
will result in
varargin
having the following contents:It will then be necessary to iterate over this cell array, parsing the options and setting/storing arguments accordingly (after converting them from character vectors to numeric values as needed). There are many ways you could implement this, depending on what option formats you want to allow. Here's an example of one way to parse the type of sample arguments you mention above:
The
opts
cell array initially stores the possible options, if they have an associated argument, and what the default value is. After parsing the input arguments, the default values will be overwritten by any values passed to the function. Theargs
cell array captures any arguments that don't match any options. Here are some sample inputs and results: