MATLAB - Classes and Object



In MATLAB, using classes and objects allows you to organize and manage complex programs more efficiently. Object-oriented programming (OOP) in MATLAB enables you to create objects that encapsulate data and functions, promoting modularity, reuse, and clarity.

Understanding Classes and Objects

  • Classes − A class is a blueprint for creating objects. It defines properties (data) and methods (functions) that the objects created from the class will have.
  • Objects − An object is an instance of a class. It contains data and functions defined by the class.

Benefits of Using Classes and Objects

  • Modularity − Break your program into smaller, manageable pieces (objects), each with a specific role.
  • Reusability − Create reusable code by defining classes that can be used across different projects.
  • Maintainability − Easier to maintain and update code as changes to a class automatically apply to all objects created from it.
  • Encapsulation − Keep data safe by restricting direct access to it and allowing modification only through defined methods.

Key Concepts

  • Properties − Variables that store data specific to an object. For example, a BankAccount class might have properties like AccountNumber and Balance.
  • Methods: Functions that operate on the object's data. For example, a BankAccount class might have methods like deposit and withdraw.

Class creation in Matlab

Creating a simple class in MATLAB involves defining a class definition file, specifying properties (data members), and methods (functions) that the class will have. Heres a step-by-step way to create a simple MATLAB class.

The very first thing you have to do is to create a file and to do that follow the steps given below ,

  • Open Matlab
  • Go to the Home tab and click on New Script to create a new file.
  • Save the file with .m extension and name your class file as MyClass.m. Remember that the name of your file has to match with the name of the class.

The screenshot of how it is done in matlab is as shown below −

The next will start defining the class

Open MyClass.m file and use the classdef keyword , here is a basic skeleton of the class.

classdef MyClass
    properties
        % Define properties (data members) here
        Property1
        Property2
    end
    
    methods
        % Define methods (functions) here
        function obj = MyClass(inputArg1, inputArg2)
            % Constructor method
            obj.Property1 = inputArg1;
            obj.Property2 = inputArg2;
        end
        
        function result = myMethod(obj, inputArg)
            % Example method
            result = obj.Property1 + inputArg;
        end
    end
end

Let us now get into the class details. First and foremost let's discuss properties.

Define Properties

Properties are data members of the class. Define them inside the properties block. For example, consider i have two properties, Property1 and Property2.

The definition of properties inside my class MyClass.m will be as follows.

properties
    Property1
    Property2
end

Once that we are done with defining the properties, we will move on to defining methods.

Defining methods of class

Methods are functions that operate on the data in the class. They are defined inside the methods block.

We have two types of methods a constructor method and regular methods.

Let us understand constructor method first

Constructor Method − This method is called when you create an instance of the class. Define it with the same name as the class.

function obj = MyClass(inputArg1, inputArg2)
    % Constructor method
    obj.Property1 = inputArg1;
    obj.Property2 = inputArg2;
end

Regular Methods − These are regular functions that operate on the class properties. Define them with any name you like.

function result = myMethod(obj, inputArg)
    % Example method
    result = obj.Property1 + inputArg;
end

Now that we have the class saved as MyClass.m, you can now create an instance of MyClass and call its methods from the MATLAB command window as shown below.

obj = MyClass(10, 20);
disp(obj.Property1)
disp(obj.Property2)
result = obj.myMethod(5)
disp(result)

On execution in matlab command window the output is −

>> obj = MyClass(10, 20);
disp(obj.Property1)
disp(obj.Property2)
result = obj.myMethod(5)
disp(result)

    10

    20

result =

    15

    15

classdef keyword in MATLAB

The classdef keyword in MATLAB is used to define a new class.

Syntax

classdef (Attributes) ClassName < SuperclassNames
    properties (Attributes) ... end
    methods (Attributes) ... end
    events (Attributes) ... end
    enumeration ... end
end

Let us understand the syntax in detail.

classdef (Attributes) ClassName < SuperclassNames

  • classdef − The keyword used to define a class.
  • Attributes − Optional attributes that specify certain properties of the class (e.g., Sealed, Abstract, HandleCompatible).
  • ClassName− The name of the class.
  • SuperclassNames − A list of one or more classes that this class inherits from (i.e., its superclass or superclasses).

Properties Block

Properties (Attributes) − Define the data attributes (properties) of the class. Properties store data specific to the object.

properties (Attributes)
     PropertyName
end

Attributes − Optional attributes that specify certain properties of the class properties (e.g., Constant, Dependent, Access).

Methods Block

Methods (Attributes) − Define the functions (methods) of the class. Methods perform operations on the objects of the class.

methods (Attributes)
    function obj = MethodName(obj, args)
    end
end

Attributes − Optional attributes that specify certain properties of the methods (e.g., Static, Abstract, Access).

Events Block

Events (Attributes) − Define the events that the class can trigger.Events allow objects to communicate changes or actions to other objects.

events (Attributes)
    EventName
end

Attributes − Optional attributes that specify certain properties of the events.

Enumeration Block

Enumeration − Define an enumeration class with a fixed set of named values. Enumeration classes are useful for defining a set of related constants.

enumeration
    EnumMember
end

Here's an example of a simple class definition.

classdef (Sealed) MyClass < SuperClass
    properties (Access = private)
        Property1
    end

    methods
        function obj = MyClass(inputArg)
            obj.Property1 = inputArg;
        end

        function output = myMethod(obj, inputArg)
            output = obj.Property1 + inputArg;
        end
    end

    events
        Event1
    end

    enumeration
        EnumMember1, EnumMember2
    end
end

In this example.

  • MyClass is a class that inherits from SuperClass.
  • The class is marked as Sealed, meaning it cannot be subclassed.
  • It has one private property, Property1.
  • It has a constructor method MyClass and another method myMethod.
  • It defines one event, Event1.
  • It has two enumeration members, EnumMember1 and EnumMember2.

class(obj) in MATLAB

The class function in MATLAB is used to determine the class (type) of an object. This function returns a character vector that specifies the class name of the input object. It is particularly useful for introspection, where you need to know the type of an object at runtime.

Syntax

className = class(obj)

In above syntax

  • obj− The object whose class type you want to determine. This can be any MATLAB variable, including arrays, structures, function handles, or objects of custom classes.
  • className: A character vector representing the name of the class of the input object obj.

Please Note

  • When you pass a built-in type (e.g., double, char, cell) to the class function, it returns the name of that type.
  • When you pass an object of a custom class, it returns the name of that class.
  • This function is useful for debugging and for writing functions that need to behave differently based on the class of their input.

Let us see a few examples.

Example 1: Built-in Types

% Determine the class of a numeric array
a = [1, 2, 3];
className = class(a)

% Determine the class of a string
str = 'Hello, World!';
className = class(str)

% Determine the class of a cell array
c = {1, 2, 3};
className = class(c)

On execution in matlab command window the output is −

>> % Determine the class of a numeric array
a = [1, 2, 3];
className = class(a)

% Determine the class of a string
str = 'Hello, World!';
className = class(str)

% Determine the class of a cell array
c = {1, 2, 3};
className = class(c)

className = double
className = char
className = cell

Example 2: Custom Class

Suppose you have a custom class MyClass defined as follows.

classdef MyClass
    properties
        Property1
        Property2
    end
    
    methods
        function obj = MyClass(inputArg1, inputArg2)
            % Constructor method
            obj.Property1 = inputArg1;
            obj.Property2 = inputArg2;
        end
        
        function result = myMethod(obj, inputArg)
            % Example method
            result = obj.Property1 + inputArg;
        end
    end
end

You can create an object of this class and use the class function to determine its type.

% Create an instance of MyClass
obj = MyClass(10, 20)

% Determine the class of the object
className = class(obj)

On execution in matlab command window the output is −

>> % Create an instance of MyClass
obj = MyClass(10, 20)

% Determine the class of the object
className = class(obj)

obj = 

  MyClass with properties:

    Property1: 10
    Property2: 20

className =

    'MyClass'

>> 

isobject() function in MATLAB

The isobject() function in MATLAB is used to determine if a variable is an object of a user-defined class. This can be particularly useful when you need to check the type of a variable before performing operations that are specific to objects.

In MATLAB, variables can belong to different data types, including numeric arrays, character arrays, structures, cell arrays, and objects. An object in MATLAB is an instance of a class, which can be either a built-in class or a user-defined class. The isobject function helps to identify if a given variable is an object.

Syntax

tf = isobject(A)

In the syntax above.

  • A − The variable you want to test.
  • tf − A logical value (true or false). It returns true if A is an object; otherwise, it returns false.

Let us see few examples

Example 1: Checking a Numeric Array

A = [1, 2, 3, 4, 5];
tf = isobject(A);
disp(['Is A an object? ', num2str(tf)]);

In the example above tf = isobject(A); checks if A is an object.

On execution in matlab command window the output is −

>> A = [1, 2, 3, 4, 5];
tf = isobject(A);
disp(['Is A an object? ', num2str(tf)]);

Is A an object? 0
>>

Example 2: Checking a Structure

The code we have is

B = struct('field1', 10, 'field2', 20);
tf = isobject(B);
disp(['Is B an object? ', num2str(tf)]);

Here tf = isobject(B); checks if B is an object.

On execution in matlab command window the output is −

>> B = struct('field1', 10, 'field2', 20);
tf = isobject(B);
disp(['Is B an object? ', num2str(tf)]);

Is B an object? 0
>> 

Example 3: Checking a User-Defined Object

First, define a custom class MyClass in a file named MyClass.m:

The code we have is.

% MyClass.m
classdef MyClass
    properties
        Property1
        Property2
    end
    
    methods
        function obj = MyClass(val1, val2)
            obj.Property1 = val1;
            obj.Property2 = val2;
        end
    end
end

Now, create an instance of this class and check if it is an object.

C = MyClass(10, 20);

tf = isobject(C);
disp(['Is C an object? ', num2str(tf)]);

In above code tf = isobject(C); checks if C is an object.

On execution in matlab command window the output is.

>> C = MyClass(10, 20);

tf = isobject(C);
disp(['Is C an object? ', num2str(tf)]);

Is C an object? 1
>> 
Advertisements