Properties and Methods

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

The reference material consulted while preparing these pages is listed in the section bibliography.

Written against MATLAB R2026b. Most of what is described here is old: property attributes and methods belong to the classdef class system (R2008a). The newer pieces are property validation (R2016a), the modular indexing classes matlab.mixin.indexing.RedefinesParen, RedefinesDot and RedefinesBrace (since R2021b), the WeakHandle property attribute (since R2024b) and its use with classes that customise indexing (since R2026a). The releases of the last three come from the "Since" notes of the R2026b pages.

GNU Octave 11.3.0 is not MATLAB here, and the differences matter on this page. Octave implements classdef only in part. The heatflow Plate class below was run in Octave 11.3.0 in a copy that has two changes: the property validation clauses are removed (Octave prints a warning that "size, class, and validation function specifications are not yet supported for classdef properties" and may give incorrect results) and SetAccess = immutable is written SetAccess = private, because Octave stops with 'immutable' undefined. Octave also has no matlab.mixin.indexing classes (the class definition stops with "class not found"). Output shown under "Octave 11.3.0 output" was captured; everything else is "not run here" and checked line by line against the R2026b documentation. Error messages from MATLAB itself are quoted only where the documentation prints them, and otherwise their wording varies by release.

What a class is made of

A class file has a classdef line followed by blocks. This page covers the two blocks that define what an object holds and what it can do: properties (the data) and methods (the operations). The other blocks, events and enumeration, and the classdef line itself with its superclasses, have their own pages (see below). Value and handle classes, which decide what assignment does to an object, are on Value and Handle Classes, and the basic syntax of a class file on classdef Basics.

Both blocks can appear many times in one class. An attribute list in parentheses after the keyword applies to every member declared in that block, so a class that needs members with different behaviour uses several blocks:

properties (Attribute1 = value1, Attribute2 = value2)
    ...
end

methods (Attribute1 = value1)
    ...
end

Two shorthands from the documentation apply to every attribute whose value is a logical. The attribute name alone means true, as in properties (Abstract), and the name with the not operator means false, as in properties (~Dependent). Attributes that are not listed keep their default values. The documentation adds a rule that is easy to miss: subclasses do not inherit the member attributes of their superclass. A subclass that redeclares a property or overrides a method states its attributes again (with the exceptions listed below for property access).

Properties

A property holds data of the object. All objects of a class have the same properties, and each object keeps its own values. The simplest block has no attributes and no defaults:

properties
    Nx
    Ny
end

Properties are read and assigned with dot notation, plate.Nx, and a property name can be built at run time with the dynamic field syntax plate.(name). Display of an object in the Command Window lists its public properties and their values.

Property attributes

All properties support the attributes of the following table, which restates the table of the documentation for R2026b.

Attribute Values (default first) What it does

Access

public, protected, private, or a list of classes

Sets GetAccess and SetAccess to the same value. public is any code, protected the defining class and its subclasses, private only the defining class. An empty cell array {} is the same as private.

GetAccess

public, protected, private, or a list of classes

Who may read the property. In the Command Window MATLAB does not display the name and value of a property whose GetAccess is protected or private.

SetAccess

public, protected, private, immutable, or a list of classes

Who may assign the property. immutable means the value can be set only in the constructor, or as a default.

Constant

false, true

The property has the same value in all instances. Subclasses inherit constant properties but cannot change them. A constant property cannot also be Dependent, and its SetAccess is ignored.

Dependent

false, true

The value is not stored in the object; a get method calculates it when the property is accessed. A dependent property can have a set method, but that method cannot actually set the value of the dependent property.

Hidden

false, true

The property is not shown in property lists, in the results of get, set or properties, or in the Command Window display. It is still visible in the Class Diagram Viewer app.

Abstract

false, true

The property has no implementation, and a concrete subclass must override it without Abstract. An abstract property cannot have get or set methods or an initial value, and a sealed class cannot define abstract members.

Transient

false, true

The value is not saved when the object is saved to a file or sent from MATLAB to another program such as a MATLAB Engine application.

NonCopyable

false, true

The value is not copied when the object is copied. It can be set to true only in handle classes.

AbortSet

false, true

For handle classes only. When true, MATLAB does not set the property or call a set method if the new value equals the current value, and the PreSet and PostSet events are not triggered.

SetObservable, GetObservable

false, true

For handle classes. Listeners can be created that are called when the property is set or queried. See Events and Listeners.

WeakHandle

false, true

Since R2024b. The property holds a weak reference to a handle object, which does not keep that object alive. The property can only take handle object arrays, must use class validation, and may have only an empty or invalid-handle default. Since R2026a it can also hold classes that inherit from RedefinesParen or overload subsref or subsasgn.

PartialMatchPriority

positive integer, default 1

Only for subclasses of matlab.mixin.SetGet: the relative priority of partial property name matches in get and set.

Access lists. Access, GetAccess and SetAccess also take a class or a cell array of classes written with the ?ClassName syntax, which gives exactly those classes (and their subclasses) the access. The documentation’s example is properties (GetAccess = {?ClassA, ?ClassB}). Access lists are not inherited: a subclass of the defining class does not get access unless it states it. Separately, all subclasses must give a property the same SetAccess and GetAccess values as the superclass; a subclass cannot loosen or tighten them.

Making a value read-only. The usual pattern for data that a class manages itself is SetAccess = private (or protected to let subclasses write it) with public reading. SetAccess = immutable is stricter: the property can be set only in the constructor or as a default, and the documentation says you cannot define a set method for it. The documentation’s example stores the creation date once:

classdef Immute
    properties (SetAccess = immutable)
        CurrentDate
    end
    methods
        function obj = Immute
            obj.CurrentDate = datetime("today");
        end
    end
end

Not run here (immutable is not available in Octave 11.3.0). The documentation shows the object displayed with a CurrentDate value and states that only the constructor can change it.

Default values and validation

A default value is written after an equals sign and is assigned when the object is created. Two rules from the documentation matter in practice. MATLAB does not call set methods when it assigns the defaults during initialisation (setting a property in the constructor does call them). And a default that is itself an object is constructed once, when the class is first loaded, and shared by all instances; for a handle class that means the instances share one object. Use the constructor to give each instance its own handle (see Value and Handle Classes).

Property validation restricts what a property can hold. After the property name you may write, in this order, a size, a class and a list of validator functions in braces, then an optional default:

PropertyName (size) class {validator1, validator2} = default

The three parts mean the following, from the documentation.

  • Size: the length of each dimension as a positive integer or a colon, so (1,3) is a 1-by-3 array and (:,:) any matrix. The value must conform to the size or be compatible with it.

  • Class: the name of one MATLAB class. The value must be of that class or convertible to it. Java and COM classes are not allowed.

  • Functions: validators such as mustBePositive, mustBeInteger, mustBeFinite, mustBeNonnegative or mustBeNumeric. They throw an error when the check fails and return nothing.

When a value is assigned, MATLAB checks in this order: class (which can convert, for example char to string), size (which can expand a scalar or reshape a column to a row), the validators from left to right (an error stops the process), and only then the set method, if there is one. Assignments made inside a set or get method do not validate again. The documentation advises using validation instead of set methods wherever it is enough, and replacing a fixed set of text options with an enumeration class (see Enumerations).

Conversion rules apply, so restricting a property to double does not stop a user assigning a single or an integer: the value is converted. To insist on the exact class, use a validator function that checks it. If you give no default, MATLAB creates one that satisfies both the size and the class: an empty value when the size allows it, an array of zeros of the declared size for a numeric class (so (1,1) double defaults to 0); the documentation tabulates the rule for the other classes. Make sure any default you write satisfies the restrictions, because defaults are validated too.

The documentation’s error example assigns a cell array to a property declared Value(1,1) double {mustBeNonnegative} = 0 and reports Error setting property 'Value' of class 'ValueProp': followed by Invalid data type. Value must be double or be convertible to double.

Get and set methods

A get method runs whenever the property is read, and a set method whenever it is assigned. They are named get.PropertyName and set.PropertyName and are written in a methods block that has no attributes (the documentation states that a block defining get or set methods cannot specify attributes). Typical uses are computing a dependent property, validating beyond what the built-in validation can do, issuing a custom error, and reacting to a change.

function value = get.PropertyName(obj)         % get method
function obj = set.PropertyName(obj,value)     % set method, value class
function set.PropertyName(obj,value)           % set method, handle class

Rules from the documentation:

  • You cannot call them directly; MATLAB calls them automatically. (A user-callable interface is a separate design, with ordinary getX and setX methods.)

  • They are not called recursively. Inside set.Value, an assignment obj.Value = v stores the value directly. This is why a set method can store what it validated.

  • A set method of a value class returns the modified object; one of a handle class does not need to.

  • Set methods are not called for the default values assigned at initialisation, but they are called when the constructor assigns a property and when an object is loaded from a file.

  • When a value object is copied, neither method is called while the property values are copied.

  • Displaying an object calls the get methods of the properties it shows. If a get method errors, MATLAB hides the error and omits that property from the display.

  • With AbortSet = true on a handle class, the set method is skipped when the new value equals the current one, but the get method is called so the two can be compared.

  • Get and set methods add overhead, so keep them light for properties accessed often.

The heatflow Plate class

The running example collects the above into the value class heatflow.Plate shared with the other pages of the section. It lives in +heatflow/Plate.m (see Namespaces and Class Folders); inside the file the class is named just Plate.

classdef Plate
    properties (Constant)
        InitialTemperature (1,1) double = 20
    end
    properties (SetAccess = immutable)
        Nx (1,1) double {mustBeInteger, mustBePositive} = 1
        Ny (1,1) double {mustBeInteger, mustBePositive} = 1
        Dx (1,1) double {mustBePositive} = 1
        Alpha (1,1) double {mustBePositive} = 1e-4
    end
    properties
        T (:,:) double {mustBeFinite}
    end
    properties (Dependent)
        NumNodes
    end
    methods
        function obj = Plate(nx, ny, dx, alpha)
            if nargin > 0
                obj.Nx = nx;
                obj.Ny = ny;
                obj.Dx = dx;
                obj.Alpha = alpha;
            end
            obj.T = heatflow.Plate.InitialTemperature * ones(obj.Ny, obj.Nx);
        end
        function obj = set.T(obj, value)
            % Compare with the current T only: reading Nx or Ny here would
            % trigger Code Analyzer message MCSUP (see the text below).
            if ~isempty(obj.T) && ~isequal(size(value), size(obj.T))
                error("heatflow:Plate:badSize", ...
                    "T must be %d-by-%d, got %d-by-%d.", ...
                    size(obj.T, 1), size(obj.T, 2), size(value, 1), size(value, 2));
            end
            obj.T = value;
        end
        function n = get.NumNodes(obj)
            n = obj.Nx * obj.Ny;
        end
        function m = maxTemperature(obj)
            m = max(obj.T, [], "all");
        end
    end
end

Not run here as written (validation and immutable are not supported by Octave). Reading it: the grid size, spacing and diffusivity are fixed at construction, so they are immutable and validated as positive scalars. Their explicit defaults satisfy the validators and the nargin > 0 guard lets the constructor run with no arguments, which MATLAB needs when it builds object arrays (see Object Arrays, Customization and Introspection); heatflow.Plate() is a 1-by-1 plate. The temperature matrix T stays public, so a simulation can update it, but its set method rejects a matrix of a different shape with an identifier a caller can test. NumNodes is derived from Nx and Ny, so it is Dependent and nothing can fall out of step. InitialTemperature is a constant: it exists once for the class and is read as heatflow.Plate.InitialTemperature. Two details of ordering are worth noting. The obvious set method would compare the new value with [obj.Ny, obj.Nx], but Code Analyzer flags a set method that reads another property (message MCSUP): MATLAB does not guarantee the order in which properties are assigned, for example when an object is loaded from a MAT-file, so T could be checked against a size that has not been restored yet. The set method therefore reads only T itself: the first assignment, made by the constructor while T is still empty, fixes the shape, and every later assignment must keep it. And because validation runs before the set method, a matrix of NaN fails mustBeFinite before the size check is reached.

Methods

A method is a function that belongs to the class. The documentation divides them into ordinary methods, which operate on objects of the class, and static methods, which do not need an object. Constructors, destructors (delete of handle classes) and property access methods are special cases.

Ordinary methods

An ordinary method takes an object, or an array of objects, of its class as an input argument, and that argument must be named explicitly: the documentation notes that MATLAB has no implicit this. The first argument is conventionally called obj. Methods compute values from the object data, can overload built-in functions, and can return modified objects. A method can be called in either of two equivalent forms:

m = maxTemperature(plate);    % function notation
m = plate.maxTemperature();   % dot notation

For a value class the method works on a copy, so a method that changes the object must return it and the caller must assign the result: plate = heat(plate, 5). Calling heat(plate, 5) and ignoring the result changes nothing, a classic bug that does not occur with handle classes (see Value and Handle Classes). The documentation’s addData example shows the same pattern, a = addData(a,75).

Method attributes

Attribute Values (default first) What it does

Access

public, protected, private, or a list of classes

Which code can call the method: any code, the class and its subclasses, or the class only. A list of classes gives access to those classes. An empty list is private.

Static

false, true

The method needs no object and is called with the class name, classname.methodname, or through an instance.

Sealed

false, true

The method cannot be redefined in a subclass; defining one with the same name is an error.

Abstract

false, true

The method has only a signature line (no function or end keywords) and subclasses implement it. Subclasses usually keep the same signature, but are not required to have the same number of arguments.

Hidden

false, true

The method name is left out of the lists shown by methods and methodsview, and ismethod does not return true for it.

A method access list works like the property one. In the documentation’s example, methods (Access = {?ClassA, ?ClassB, ?MethodAccess}), the two classes can call listMethod and so can subclasses of MethodAccess, because it is in its own list; had it not been, its subclasses could not redefine the method.

Static methods

A static method is tied to the class, not to an instance. It is useful for factory functions, for setting up the environment before an object exists, and for calculating data needed to build instances. It is defined in a methods (Static) block and called with the class name, or on an instance; subclasses may redefine it unless it is also Sealed.

methods (Static)
    function p = square(n)
        p = heatflow.Plate(n, n, 0.01, 1e-4);
    end
end

The call is plate = heatflow.Plate.square(5). Static methods take no obj argument; if the first argument is an object, the method is not static.

Methods in separate files

A class can keep its methods in separate files by putting the class in a class folder, a folder whose name is @ followed by the class name. The folder must contain the main file ClassName.m with the classdef block, and any other function file in it is a method of the class. The parent of the class folder must be on the path (the folder holding the top-level namespace folder, when the class folder lies inside one).

  • A method file is a plain function file, without methods/end around it. For readability, declare the signature in the classdef file too. You must declare it there when the method needs non-default attributes. The documentation’s example declares output = myFunc(obj,arg1,arg2) under methods (Access = private) with no function or end keywords.

  • When you add a method whose signature is not declared in the classdef file, call clear classes (or clear on the class name) so the running session notices it.

  • Static methods are declared in a methods (Static) block in the classdef file and implemented in separate files.

  • Some methods cannot be in separate files: the constructor, any function whose name contains a dot (the converters of classes in namespaces, and the property get and set methods).

  • The files can be .m, .mlx, MEX files or P-code files.

Operator overloading

Every operator in MATLAB is an ordinary function (a + b calls plus(a,b)), so a class overloads an operator by defining a method with that function’s name. Overloaded operators keep the precedence of the original operator (see Operators and Precedence). A user-defined class has higher precedence than a built-in class, so in q + p and p + q, with q a double and p an object, MATLAB calls the plus method of the user-defined class if it exists. How the two are combined is up to your method.

The documentation’s table maps operations to method names. The main ones:

Operation Method Description

a + b, a - b, -a, +a

plus, minus, uminus, uplus

Addition, subtraction, unary minus, unary plus.

a.*b, a*b

times, mtimes

Element-wise and matrix multiplication.

a./b, a/b, a.\b, a\b

rdivide, mrdivide, ldivide, mldivide

Element-wise and matrix right and left division.

a.^b, a^b

power, mpower

Element-wise and matrix power.

a < b, a > b, a <= b, a >= b, a ~= b, a == b

lt, gt, le, ge, ne, eq

Relational operators.

a & b, a | b, ~a

and, or, not

Logical operators.

a', a.'

ctranspose, transpose

Complex conjugate transpose and transpose.

[a b], [a; b]

horzcat, vertcat

Concatenation.

a(s1,...,sn), a(s1,...,sn) = b

subsref, subsasgn

Indexed reference and assignment (see the next section).

a:b, a:d:b

colon

Colon operator.

For heatflow, adding a number to a plate should raise every node temperature, two plates are equal when their data are, and the plate should print compactly. These methods go in the methods block of Plate, in the form that was run in Octave 11.3.0 (the isa test works whichever way the operands come):

function r = plus(a, b)
    if isa(a, "heatflow.Plate")
        r = a;
        delta = b;
    else
        r = b;
        delta = a;
    end
    r.T = r.T + delta;
end
function tf = eq(a, b)
    tf = isequal(a.T, b.T) && a.Dx == b.Dx && a.Alpha == b.Alpha;
end
function disp(obj)
    fprintf("Plate %d-by-%d, max %.1f degC\n", obj.Ny, obj.Nx, obj.maxTemperature());
end

The class also has the static method square shown above. The following script exercises it (the Octave copy of the class differs from the listings in three ways: single-quoted text, max(obj.T(:)) instead of max(obj.T, [], "all"), and the changes to validation and immutable described at the top). Octave 11.3.0 output:

p = heatflow.Plate(4, 3, 0.01, 1e-4);
disp(p.NumNodes)
disp(heatflow.Plate.InitialTemperature)
hot = p + 5;
disp(p.maxTemperature())
disp(hot.maxTemperature())
disp(hot)
disp(p == hot)
disp(p == p)
s = heatflow.Plate.square(5);
disp(s.NumNodes)
try
    p.Nx = 10;
catch err
    disp(err.message)
end
try
    p.T = zeros(2, 2);
catch err
    disp(err.identifier)
    disp(err.message)
end
12
20
20
25
Plate 3-by-4, max 25.0 degC
0
1
25
subsasgn: property 'Nx' has private access and cannot be set in this context
heatflow:Plate:badSize
T must be 3-by-4, got 2-by-2.

Octave 11.3.0 output; MATLAB prints its own, differently worded, message for the assignment to Nx, which is immutable there, and the max(...) call differs as stated above. The plus result shows value semantics at work: p still has maximum 20 after hot = p + 5. The same run also showed that Octave raises no error when a script assigns a dependent property that has no set method (p.NumNodes = 3 was silently accepted), while the MATLAB documentation says a dependent property without a set method cannot be assigned; do not rely on Octave’s leniency.

A note on disp. Overloading disp is the oldest way to change how an object is shown. For richer control (a header, grouped properties, different display for scalars and arrays), inherit from matlab.mixin.CustomDisplay, covered on Object Arrays, Customization and Introspection. The documentation’s own overview of class customisation lists operator overloading, mixins and function overloading as the three routes.

Customising indexing

Objects support array indexing with no extra code: plates(3) returns the third element of an object array, and plates(2,3) = p assigns one. Many class designs need nothing else. Customising indexing is for classes whose obj(...), obj.name or obj{...} should mean something other than the default, such as a container that stores its data in a private property.

Modular indexing (recommended, since R2021b). Inherit from one or more of these abstract superclasses in the matlab.mixin.indexing namespace. Each is responsible for one family of operations, and you can inherit from them independently; operations you do not customise keep the default behaviour.

Superclass Operations Abstract methods to implement

RedefinesParen

Parentheses reference, assignment and deletion.

parenReference, parenAssign, parenDelete, parenListLength, and the specialised cat, empty (static) and size.

RedefinesDot

Dot property reference, method call and assignment.

dotReference, dotAssign, dotListLength (it also provides concrete parenDotAssign and parenDotListLength).

RedefinesBrace

Brace reference and assignment.

braceReference, braceAssign, braceListLength.

The documentation’s example class ArrayWithLabel inherits from RedefinesParen and forwards parentheses indexing to a private ContainedArray property, implementing all of the abstract methods. Not run here; read the example on the class page before writing your own, because the methods must decide what to do with the indexing operations that follow the first one, as the example forwards them to MATLAB.

The legacy route. Before R2021b, a class customised indexing by overloading subsref and subsasgn. These methods receive the object and an indexing structure s (an array with type and subs fields describing each step of an expression such as obj(2).Label) and must handle every case themselves. They are still supported, and the documentation keeps a page of code patterns for them, but for R2021b and later it recommends the modular classes. The two approaches do not mix: a class that inherits from the modular indexing classes cannot overload subsref and subsasgn. Where a class overloads subsref, also review numArgumentsFromSubscript, which controls how many values an indexing expression returns.

Pitfalls

Mistake What to do

Calling heat(plate, 5) on a value class and expecting plate to change.

Return the object and assign it, plate = heat(plate, 5), or use a handle class.

A set method that reads other properties (Code Analyzer message MCSUP), which may not be assigned yet when the object is constructed or loaded.

Read only the property itself in its set method, as set.T of Plate does, and check rules that involve several properties in the constructor or in an ordinary method.

Expecting a property declared double to reject a single or an integer.

Validation converts. Add a validator that checks the exact class if it matters.

Writing a set method that only checks the class or size.

Use property validation; keep set methods for rules and side effects that validation cannot express.

Giving a default value that violates the validation.

Defaults are validated too; supply a conforming one.

Using an object as a default and expecting a fresh one per instance.

A default object is built once when the class loads. Create per-instance objects in the constructor.

Defining a Dependent property that stores a value, or a set method for it that assigns it.

The value must be computed in the get method; a set method may only act on other properties.

Combining Constant and Dependent, or giving an Abstract property a default.

Not allowed by the documentation.

Writing set.X or get.X in a block with attributes, or in a separate file.

They go in a plain methods block of the classdef file.

Changing a subclass property’s SetAccess or GetAccess from the superclass’s value.

All subclasses must use the same values as the superclass.

Overloading subsref in a class that inherits RedefinesParen.

Pick one approach; prefer the modular classes.

Relying on Octave’s classdef for the checks on this page.

Octave 11.3.0 ignores validation, lacks immutable, and does not stop assignments to dependent properties without set methods.

Where older books differ

Older books describe classes from the first releases of classdef (R2008a), and most of what they say about properties and methods still holds: attributes, get and set methods, static methods, operator overloading and class folders all work as they did. What they lack is newer. Property validation with size, class and validators in the property block (R2016a and later) replaces many of the hand-written set methods that older code uses to check types, and SetAccess = immutable is a stricter alternative to a private set that is written once. Customised indexing in older books means subsref and subsasgn only; since R2021b the modular RedefinesParen, RedefinesDot and RedefinesBrace classes are the recommended route, and the two cannot be mixed in one class. Books written before R2024b know nothing of WeakHandle. Older code also writes a set method that only checks isnumeric or isscalar: replace it with (1,1) double, and keep a set method for behaviour such as updating a related property.