Here's one take:
1) In Matlab, if you use
varargin, then you must provide all preceding optional arguments (that is,
optional must be given as well as
optional2). In this case (for example, if you call
somefxm(myarg, myarg2, myoptarg, myoptarg2), then you know based on the length of
varargin (2) that only
optional3 needs a default applied. You can have an if statement that says something like
if length(varargin) == 2
optional3 = 3; % or whatever
You can have additional conditional statements to handle having only one optional argument (e.g.
length(varargin) == 1) or no optional arguments (e.g.
length(varargin) == 0).
2) Note that with this scheme, Matlab has no clever way of knowing which function argument fits into which option, so you must keep everything in sequential order. If you need more flexibility, you can do something sort of like keyword arguments by preceding the argument with a descriptive string, which is the way that some common functions like
plot work. Then you either need to write logic to parse
varargin (as in Christian Clason's comment), or you can use the
Another (in my opinion, clunkier) way of treating an "empty"
optional2 is to test whether the provided argument is simply an empty matrix, with
optional2 = 3; % or whatever
Then, you could call
somefxn with an "empty" second optional argument as:
somefxn(myarg, myarg2, myoptarg, , myoptarg3)
Then, the second optional argument will be assigned whatever you've coded into the function. If you do this, you need to make sure that an empty matrix is not an otherwise valid argument to
somefxn, otherwise you'll have just overloaded the proper behaviour.