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

后端 未结 4 1664
别那么骄傲
别那么骄傲 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:02

    Matlab provides an 'inputParser' which allows to check inputs. Besides this you can use assertions:

    assert(islogical(yes_or_no),'logical input expected')
    

    To ensure the correct number of input arguments, use narginchk.

    btw: Take a look in some Matlab functions like edit integral and check how tmw deals with this.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-04 04:15

    I've gotten some great responses so I can't pick just one as the "accepted answer", but to summarize what I've learned from you all so far:

    • No, MATLAB does not have built-in strict data typing for function input arguments
    • MATLAB compiles the code before running, so manual validation checking should not be very taxing on performance (the profiler can be used to assess this)
    • Many helpful methods of doing the manual validation checking exist, listed here in order of most relevant to least relevant for what I was trying to do:
      • inputParser class
      • validateattributes()
      • Error/exception handling (throw(), error(), assert(), etc.)
      • MATLAB's built-in state detection functions (a.k.a predicate functions)
    • I can look through some MathWorks-provided MATLAB functions (or Statistics toolbox functions) for ideas on how to validate input arguments by typing edit followed by the function name. Two suggested functions to look at are normpdf() (from the Statistics toolbox) and integral(). Some other functions I found helpful to look at are dot() and cross().

    Other thoughts:

    • It would appear that the inputParser class was the overall concensus on the most professional way to validate input arguments. It was noted on a related (but not duplicate) stackoverflow post that the newer MathWorks functions tend to make use of this class, suggesting that it may be the best and most up-to-date choice.
    • Since the MathWorks-provided MATLAB functions do not appear to enforce strict input argument data typing, this further suggests that even if it was possible to do so, it may not be a recommended approach.
    • MATLAB seems to regard "error handling" and "exception handling" as two different concepts. For example, here are two links to MATLAB's Documentation Center that show how MathWorks considers "error handling" and "exception handling" differently: MathWorks Documentation Center article on Error Handling, MathWorks Documentation Center article on Exception Handling. A relevant StackOverflow post has been made on this topic and can be found here (link). I contacted MathWorks and added some new information about this topic to that post, so if you are interested you may read more by following that link.
    0 讨论(0)
  • 2021-01-04 04:25

    validateattributes might also work for you, if there is an appropriate attribute for your case. For example if you want to enforce that yes_or_no is a logical scalar, you could try:

    validateattributes(yes_or_no,{'logical'},{'scalar'})
    

    Otherwise maybe an attribute like 'nonempty'.

    0 讨论(0)
提交回复
热议问题