MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Error using checkme (line 3)
Expected input to be positive.


checkme(pi,rand(3,4,2))


Error using checkme (line 4)
Expected input to be an array with number of elements equal to 100.


checkme(pi,rand(5,10,2),struct)


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)


validateattributes(a,{'double'},{'positive','2d'},'','First',1)
validateattributes(b,{'numeric'},{'numel',100,'ncols',10},'','Second',2)
validateattributes(c,{'char'},{'nonempty'},'','Third',3)


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.


checkdetails(-4)


Error using checkdetails (line 3)
Expected input number 1, First, to be positive.


Check Function Inputs with validateattributes
Free download pdf