What is the best way to check the inputs of a function?

4 views (last 30 days)
What is the best way to check the inputs of a function in Matlab?
So far I found two 'nice options':
  1. Function argument validation
  2. validateattributes
What do you think it is the best way? (Also, I have already started using validateattributes and I was wondering if I should change).
Thank you!
  4 Comments
Stephen23
Stephen23 on 24 Apr 2023
"I would say i do not care about backward compatibility, but i do generally care about the other points"
Then probably Function argument validation would be the right choice: neat, simple, easy to use...

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 24 Apr 2023
I'm sure there are varying opinions on this. Here are some bits that might help with your decision.
  • function argument validation was introduced in R2019b. Will the users of your function all use a release on or after 19b?
  • you may find that error messages created by functional argument validation are more intuitive or simpler to understand
  • is readability and organization important to you? The functional argument validation is neatly tucked away at the top of the code whereas validateattributes could be sprinkled throughout.
  • does functional argument validation or validateattributes have the validation options you need?
As a MATLAB user in grad school, when the new function argument validation feature was released, it took me a while to convert from using validateattributes, primarily because most of the analysis software I wrote needed to function on machines that did not have MATLAB R2019b or later but also because I already was comfortable with validateattributes/validatestring/etc. When I switched over to using the new argument validation feature, I soon felt like it delivered a more consistent experience for the developer and for the user.
  3 Comments
Adam Danz
Adam Danz on 24 Apr 2023
I haven't compared performance between validation techniques but I've wondered about this, too.
Lorenzo
Lorenzo on 24 Apr 2023
Thank you for your answer, this is is pretty useful. I will stick with validateattributes since i have already 10/15 functions with it. I might switch when i have some time.

Sign in to comment.

More Answers (0)

Categories

Find more on Argument Definitions in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!