MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Validate Property and Input Values


This example shows how to verify that the user’s inputs and property values are valid.

Validate Properties

This example shows how to validate the value of a single property using
set.PropertyName syntax. In this case, the PropertyName is Increment. Validate the
value of two interdependent properties using the validatePropertiesImpl method. In
this case, the UseIncrement property value must be true and the WrapValue property
value must be less than the Increment property value.

methods
% Validate the properties of the object
function set.Increment(obj,val)
if val >= 10
error("The increment value must be less than 10");
end
obj.Increment = val;
end
end
methods (Access = protected)
function validatePropertiesImpl(obj)
if obj.UseIncrement && obj.WrapValue > obj.Increment
error("Wrap value must be less than increment value");
end
end
end

Validate Inputs

This example shows how to validate that the first input is a numeric value.

methods (Access = protected)
function validateInputsImpl(~,x)
if ~isnumeric(x)
error("Input must be numeric");
end
end
end

Complete Class Definition File with Property and Input Validation

classdef AddOne < matlab.System
% ADDONE Compute an output value by incrementing the input value

34 System object Usage and Authoring

Free download pdf