File Exchange Pick of the Week

Our best user submissions

New with R2019b – Function Argument Validation

Jiro‘s Pick this week is Function Argument Validation, which is a new R2019b feature that I’m really excited about.

If you search for “function argument validation” or “input validation” in File Exchange, you will see quite a few entries on it. Some are actual utilities for doing validation, while others are regular entries with validation functions within them. There are also argument parsing entries for parsing optional arguments.

Input validation can be a tedious task and may require thorough consideration of logic to ensure robust code. Let’s look at an example.

Let’s say that I want to create a function that takes an arbitrary number of data sets and creates an overlapping histogram. In addition, I’d like the function to take optional param-value pair inputs to customize some properties of the plot. So the input argument looks something like this:

  myhistogram(DATA1, DATA2, ..., PARAM1, VALUE1, PARAM2, VALUE2, ...)

You can imagine how tricky this may be to implement. Doable, but tedious. I would need to do some parsing to first see how many data sets are passed in. I may do that by checking from the first input to see if it is not a parameter name I’m looking for. After that, I repeatedly inspect the parameter-value pairs and assign the values to the appropriate parameters. Again, doable, but tedious.

With the new function argument validation, the parsing and the validation can be expressed in a compact, easy-to-understand way. Here is the whole code:

Let’s see how it works.

data1 = randn(2000,1);
data2 = 1 + randn(5000,1);
data3 = 3 + randn(4000,1);
myhistogram(data1,data2,data3)

I can call it with some parameters

myhistogram(data1,data2,data3,'nbins',25,'showlegend',true)

If I mistype my parameters, the validation functions catch the error.

try
    myhistogram(data1,data2,data3,'nbins',5.5,'showlegend',true)
catch ME
    disp(ME.message)
end
Invalid name-value argument 'nbins'. Value must be integer.

Comments

Give it a try and let us know what you think here.




Published with MATLAB® R2019b

|
  • print

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.