Search code examples
matlab

Handle missing arguments without knowing number of arguments


function out = fn(a, b, z)
end

Problem: function whose argument count may change in the future, but the name of last argument stays same. Need to check whether last argument was passed in or not.

Solution attempt: nargin requires counting the number of arguments, and AFAIK, no easy way to get a function's number of input arguments. So, do

try
    z
catch
    z = 'whatever';

Yet, it's clearly a hack and not ideal.

Is there a better way? Like nmissingargin? Assume all arguments are positional (but this is flexible).

Note: I'm aware of fn(a, b, C) ... arguments a; b; C.z = 'whatever' - too much code.


Solution

  • Thanks @CrisLuengo -- use exist:

    function out = fn(a, b, z)
        if ~exist('z', 'var')
            z = 'whatever';
        end
    end