nargin vs exist

前端 未结 6 2044
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 06:46

Given a function like:

function foo(myParam)
if nargin<1
  myParam = \'default value\';
end % if
end % function

I\'ve seen people use so

6条回答
  •  长情又很酷
    2020-12-30 07:08

    I strongly prefer exist over the nargin option for two reasons.

    1. After reading a lot of code from people who were never taught to look back at their own code, I have only felt stronger for this, as exist makes the code readable. For example, I encountered once a function like this. For your convenience I gave the variables sensible names:

    [model, accuracy] = epicModelingFunction (dataMatrix, responseVector, indicatorForCategoricalVariables, optionsForInternalFunctions, typeOfDistanceCalculation, notationForMissingValues, isClassificationAndNotRegression, scalingMethod, shouldPlotAllIntermediateStuff)
    % EPICMODELINGFUNCTION is actually a horrible function to read and not epic at all
    % ...
    

    This was then followed by if nargin < n for every variable other than the first two. The only reason I could follow what the nargin(n) should be without counting the header input, is that the if nargin < n was always followed by (only sometimes a few lines of code and) the declaration of the missing input with the default value. For bigger chucks of code in the if nargin < n, I would definitely lose track.

    2. exist doesn't really check the complete workspace if called from a function. Sure, comparing two numbers is less expensive as comparing a few strings, but if used at the beginning of a function to fill in default values for the not given parameters, it is fine. Consider the following function:

    function testExist(C)
    if exist('B', 'var')
        disp('''exist'' in a function checks the workspace.')
    elseif exist('C', 'var')
        disp('''exist'' in a function ignores the variables in the workspace, but checks the function space.')
    else
        disp('''exist'' is broken or no parameter was given.')
    end
    end
    

    And then executing the following:

    A = magic(3);
    B = magic(4);
    testExist(A)
    

    results in this output:

    'exist' in a function ignores the variables in the workspace, but checks the function space.
    

提交回复
热议问题