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.

 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
  

This example shows how to 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 (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
  
  % All properties occur inside a properties declaration.
  % These properties have public access (the default)
  properties (Logical)
    UseIncrement = true
  end

  properties (PositiveInteger)
    Increment = 1
    WrapValue = 10
  end

  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
    
    % Validate the inputs to the object
    function validateInputsImpl(~,x)
        if ~isnumeric(x)
          error('Input must be numeric');
        end
    end
        
    function out = stepImpl(obj,in)
      if obj.UseIncrement
        out = in + obj.Increment;
      else
        out = in + 1;
      end
    end    
  end
end

See Also

|

Related Examples

More About

Was this topic helpful?