Property Class and Size Validation - MATLAB & Simulink (2024)

Property Class and Size Validation

Property Class and Size

MATLAB® applies any class and size validation defined for a property before calling validation functions. Assignment to a property that defines size or class validation is analogous to assignment to a MATLAB object array. MATLAB can apply class and size conversions to the right side of the assignment to satisfy class and size validation.

For more information, see Order of Validation and Property Validation Functions.

Property Size Validation

Specify the property size as the row, column, and additional dimension following the property name.

classdef MyClass properties Prop(dim1,dim2,...) = defaultValue endend

Assignment and Size Validation

This class defines the size of the Location property as 1-by-3. Any value assigned to this property must conform to that size or must be convertible to that size.

classdef ValidateProps properties Location(1,3) endend

The implicit default value assigned by MATLAB, [0 0 0], conforms to the specified size:

a = ValidateProps
a = ValidateProps with properties: Location: [0 0 0]

MATLAB applies scalar expansion when you assign a scalar the Location property.

a = ValidateProps;a.Location = 1
a = ValidateProps with properties: Location: [1 1 1]

MATLAB converts columns to rows to match the size specification:

col = [1;1;1]
col = 1 1 1
a.Location = col
a = ValidateProps with properties: Location: [1 1 1]

Colon in Size Specification

A colon in the size specification indicates that the corresponding dimension can have any length. For example, you can assign a row vector with any number of columns to the Data property in this class.

classdef ValidateProps properties Data(1,:) endend
a = ValidateProps;a.Data = [1:10]
a = ValidateProps with properties: Data: [1 2 3 4 5 6 7 8 9 10]

Assignment to a property that defines size validation follows the same rules as the equivalent indexed array assignment. For information on indexing behavior of multidimensional arrays, see Compatible Array Sizes for Basic Operations.

Property Class Validation

Defining the class of a property can reduce the need to test the values assigned to the property in your code. In general, the value assigned to the property must be of the specified class or convertible to the specified class. An exception to this rule is for subclasses. If you specify a user-defined class as part of validation, subclasses of that class pass validation without error, but they are not converted.

You can specify only one class per property. Use validation functions like mustBeNumeric or mustBeInteger to restrict properties to a broader category of classes. For more information on validation functions, see Property Validation Functions.

You can use any MATLAB class or externally defined class that is supported by MATLAB, except Java® and COM classes.

Place the name of the class in the property definition block following the property name and optional size specification.

classdef MyClass properties Prop ClassName = defaultValue endend

If you do not specify a default value, MATLAB assigns an empty object of the specified class to the property. If you define a size and a class, MATLAB attempts to create a default value for the property that satisfies both the size and class requirement.

MATLAB creates the default value by calling the class constructor with no arguments. The class must have a constructor that returns an object of the specified size when called with no input arguments or you must specify a default value for the property that satisfies the property size restriction. For more information, see Default Values Per Size and Class.

Using Class Validation

The PropsWithClass class defines two properties with class definitions:

  • Number — Values must be of class double or convertible to double.

  • Today — Values must be of class string or convertible to string. The default value is the current date, returned by the datetime function.

classdef PropsWithClass properties Number double Today string = datetime("today") endend

Create an object of the PropsWithClass class.

p = PropsWithClass
p = PropsWithClass with properties: Number: [] Today: "09-Jun-2022"

MATLAB performs conversions from any compatible class to the property class. For example, assign a uint8 value to the Number property.

p.Number = uint8(5);disp(class(p.Number))

Because the uint8 value can be converted to double, you can assign that uint8 value to the Number property.

Assigning an incompatible value to a property that uses class validation causes an error.

p.Number = datetime("today");
Error setting property 'Number' of class 'PropsWithClass':Value must be double or be convertible to double.

User-Defined Class for Validation

You can define a class to control the values assigned to a property. Enumeration classes enable users to set property values to character vectors or string scalars with inexact name matching.

For example, suppose that there is a class that represents a three-speed mechanical pump. You can define an enumeration class to represent the three flow rates.

classdef FlowRate < int32 enumeration Low (10) Medium (50) High (100) endend

The Pump class has a method to return the current flow rate in gallons per minute. Define the Speed property as a FlowRate class.

classdef Pump properties Speed FlowRate end methods function getGPM(p) if isempty(p.Speed) gpm = 0; else gpm = int32(p.Speed); end fprintf('Flow rate is: %i GPM\n',gpm); end endend

Users can set the Speed property using inexact text.

p = Pump;p.Speed = 'm'
p = Pump with properties: Speed: Medium

The numerical value is available from the property.

getGPM(p)
Flow rate is: 50 GPM

For information about enumeration classes, see Define Enumeration Classes.

Integer Class Validation

MATLAB supports several integer classes (see Integers). However, restricting a property to an integer class can result in integer overflow. The resulting value can saturate at the maximum or minimum value in the integer’s range.

When integer overflow occurs, the value that is assigned to a property can be a value that is different from the value from the right side of the assignment statement.

For example, suppose that you want to restrict a property value to a scalar uint8.

classdef IntProperty properties Value(1,1) uint8 endend

Assigning a numeric value to the Value property effectively casts the numeric value to uint8, but does not result in an error for out-of-range values.

a = IntProperty;a.Value = -10;disp(a.Value)
0

Assignment to the Value property is equivalent to indexed assignment of an array. If the assigned value is out of the range of values that uint8 can represent, MATLAB sets the value to the closest value that it can represent using uint8.

a = uint8.empty;a(1) = -10
a = uint8 0

To avoid the potential for integer overflow, use a combination of validation functions that restrict the value to the intended range instead of an integer class.

classdef IntProperty properties Value(1,1) {mustBeInteger, mustBeNonnegative,... mustBeLessThan(Value,256)} endend

Because there is no conversion of the assigned value by the uint8 class, the validators catch out of range values and throw an appropriate error.

a = IntProperty;a.Value = -10;
Error setting property 'Value' of class 'IntProperty':Value must be nonnegative.

Default Values Per Size and Class

Any default property value that you assign in the class definition must conform to the specified validation.

Implicit Default Values

MATLAB defines a default value implicitly if you do not specify a default value in the class definition. This table shows how size and class determine the implicit default value of MATLAB classes.

SizeClassImplicit Default Assigned by MATLAB

(m,n)

Any numeric

m-by-n array of zeros of specified class.

(m,:) or (:,n)

Any class

m-by-0 or 0-by-n of specified class.

(m,n)

char

m-by-n char array of spaces.

(m,n)

cell

m-by-n cell array with each cell containing a 0-by-0 double.

(m,n)

struct

m-by-n struct

(m,n)

string

m-by-n string

(m,n)

enumeration class

First enumeration member defined in the class.

(1,1)

function_handle

Runtime error — define a default value in the class.

To determine the implicit default value for nonzero and explicit size specifications, MATLAB calls the default class constructor and builds an array of the specified size using the instance returned by the constructor call. If the class does not support a default constructor (that is, a constructor called with no arguments), then MATLAB throws an error when instantiating the class containing the validation.

If the specified size has any zero or unrestricted (:) dimensions, MATLAB creates a default value that is an empty array with the unrestricted dimension set to zero.

For heterogeneous arrays, MATLAB calls the matlab.mixin.Heterogeneous.getDefaultScalarElement method to get the default object.

Related Topics

  • Validate Property Values
  • Property Validation Functions
  • Enumerations for Property Values
Property Class and Size Validation
- MATLAB & Simulink (2024)

References

Top Articles
Grandma’s Zeppole Italian Doughnuts {So Fluffy & Light!}
25 classic American recipes - Justforfruits
Kostner Wingback Bed
Spectrum Gdvr-2007
Nybe Business Id
Christian McCaffrey loses fumble to open Super Bowl LVIII
Uti Hvacr
Part time Jobs in El Paso; Texas that pay $15, $25, $30, $40, $50, $60 an hour online
Breaded Mushrooms
oklahoma city for sale "new tulsa" - craigslist
Achivr Visb Verizon
Gas Station Drive Thru Car Wash Near Me
Theycallmemissblue
Zürich Stadion Letzigrund detailed interactive seating plan with seat & row numbers | Sitzplan Saalplan with Sitzplatz & Reihen Nummerierung
Babyrainbow Private
60 X 60 Christmas Tablecloths
Fdny Business
Csi Tv Series Wiki
Walgreens Tanque Verde And Catalina Hwy
Ein Blutbad wie kein anderes: Evil Dead Rise ist der Horrorfilm des Jahres
Samantha Aufderheide
Raw Manga 1000
Boxer Puppies For Sale In Amish Country Ohio
Dtm Urban Dictionary
Walgreens On Bingle And Long Point
2015 Kia Soul Serpentine Belt Diagram
Hrconnect Kp Login
Myaci Benefits Albertsons
Hoofdletters voor God in de NBV21 - Bijbelblog
Tra.mypatients Folio
AP Microeconomics Score Calculator for 2023
Agematch Com Member Login
Zero Sievert Coop
Devotion Showtimes Near The Grand 16 - Pier Park
Legit Ticket Sites - Seatgeek vs Stubhub [Fees, Customer Service, Security]
Linda Sublette Actress
Wilson Tattoo Shops
The Conners Season 5 Wiki
ESA Science & Technology - The remarkable Red Rectangle: A stairway to heaven? [heic0408]
FREE - Divitarot.com - Tarot Denis Lapierre - Free divinatory tarot - Your divinatory tarot - Your future according to the cards! - Official website of Denis Lapierre - LIVE TAROT - Online Free Tarot cards reading - TAROT - Your free online latin tarot re
Sour OG is a chill recreational strain -- just have healthy snacks nearby (cannabis review)
Collision Masters Fairbanks
Reilly Auto Parts Store Hours
20 Mr. Miyagi Inspirational Quotes For Wisdom
Maplestar Kemono
Nurses May Be Entitled to Overtime Despite Yearly Salary
Automatic Vehicle Accident Detection and Messageing System – IJERT
8663831604
Sdn Dds
Ippa 番号
Factorio Green Circuit Setup
Latest Posts
Article information

Author: Mrs. Angelic Larkin

Last Updated:

Views: 5919

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Mrs. Angelic Larkin

Birthday: 1992-06-28

Address: Apt. 413 8275 Mueller Overpass, South Magnolia, IA 99527-6023

Phone: +6824704719725

Job: District Real-Estate Facilitator

Hobby: Letterboxing, Vacation, Poi, Homebrewing, Mountain biking, Slacklining, Cabaret

Introduction: My name is Mrs. Angelic Larkin, I am a cute, charming, funny, determined, inexpensive, joyous, cheerful person who loves writing and wants to share my knowledge and understanding with you.