Is it possible to enforce input argument data types in MATLAB?

后端 未结 4 1693
别那么骄傲
别那么骄傲 2021-01-04 03:41

I would like to ensure that the input arguments to a user-defined MATLAB function (contained in an m-file) are of a certain type. I understand that MATLAB automatically assi

4条回答
  •  爱一瞬间的悲伤
    2021-01-04 04:03

    You may find writing this sort of code tedious or worry that it degrades performance:

    if ~islogical(yes_or_no) && ~isscalar(yes_or_no)
        error('test:NotLogicalType','Second argument must be logical (Boolean).');
    end
    if yes_or_no
        y = 2 .* x;
    else
        y = -5 .* x;
    end
    

    Recall, however, that Matlab compiles the code before running so even if you need to test many conditions it will be quite fast. Run the profiler to see.

    Another option in some cases (maybe not your example) is to use a lazier method. This option lets your code run with whatever inputs were provided, but uses a try/catch block to trap any error:

    try
        if yes_or_no
            y = 2 .* x;
        else
            y = -5 .* x;
        end
    catch me
        ...
        error('test:NotLogicalType','Second argument must be logical (Boolean).');
        % rethrow(me);
    end
    

    The code above would produce an error if yes_or_no was a cell array for example (it will still allow non-Boolean, non-scalar, etc. values for yes_or_no though, but Matlab is often overly permissive). You can then either generate a custom error message, detect, what kind of error was thrown and try something else, etc. Many of the functions in the Statistics toolbox use this approach (e.g., type edit normpdf in your command window) for better or worse.

提交回复
热议问题