This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Check Function Inputs with validateattributes

Verify that the inputs to your function conform to a set of requirements using the validateattributes function.

validateattributes requires that you pass the variable to check and the supported data types for that variable. Optionally, pass a set of attributes that describe the valid dimensions or values.

Check Data Type and Other Attributes

Define a function in a file named checkme.m that accepts up to three inputs: a, b, and c. Check whether:

  • a is a two-dimensional array of positive double-precision values.

  • b contains 100 numeric values in an array with 10 columns.

  • c is a nonempty character vector or cell array.

function checkme(a,b,c)


disp('All inputs are ok.')

The curly braces {} indicate that the set of data types and the set of additional attributes are in cell arrays. Cell arrays allow you to store combinations of text and numeric data, or character vectors of different lengths, in a single variable.

Call checkme with valid inputs.

All inputs are ok.

The scalar value pi is two-dimensional because size(pi) = [1,1].

Call checkme with invalid inputs. The validateattributes function issues an error for the first input that fails validation, and checkme stops processing.

Error using checkme (line 3)
Expected input to be positive.
Error using checkme (line 4)
Expected input to be an array with number of elements equal to 100.
Error using checkme (line 5)
Expected input to be one of these types:

  char, cell

Instead its type was struct.

The default error messages use the generic term input to refer to the argument that failed validation. When you use the default error message, the only way to determine which input failed is to view the specified line of code in checkme.

Add Input Name and Position to Errors

Define a function in a file named checkdetails.m that performs the same validation as checkme, but adds details about the input name and position to the error messages.

function checkdetails(a,b,c)


disp('All inputs are ok.')

The empty character vector '' for the fourth input to validateattributes is a placeholder for an optional function name. You do not need to specify a function name because it already appears in the error message. Specify the function name when you want to include it in the error identifier for additional error handling.

Call checkdetails with invalid inputs.

Error using checkdetails (line 3)
Expected input number 1, First, to be positive.
Error using checkdetails (line 4)
Expected input number 2, Second, to be an array with
number of elements equal to 100.

See Also