MATLAB - Classes and Object
MATLAB - Modern Object-Oriented Programming
Section titled “MATLAB - Modern Object-Oriented Programming”Object-Oriented Programming (OOP) in MATLAB is a powerful paradigm for designing and implementing complex software systems. By creating classes and objects, you can build modular, reusable, and maintainable code that models real-world entities and their interactions.
Core Concepts of OOP
Section titled “Core Concepts of OOP”- Class: A template or blueprint for creating objects. It defines a set of properties (data) and methods (functions) that its objects will possess.
- Object: An instance of a class. It holds specific data in its properties and can perform actions using its methods.
- Encapsulation: Bundling data (properties) and the methods that operate on that data within a single unit (the object). This hides the internal complexity and protects data from unauthorized access.
- Inheritance: Creating a new class (a subclass) from an existing class (a superclass). The subclass inherits properties and methods from the superclass, allowing for code reuse and the creation of specialized classes.
- Polymorphism: The ability for different classes to respond to the same method call in their own unique ways. This allows for flexible and extensible code.
Defining a Modern MATLAB Class
Section titled “Defining a Modern MATLAB Class”Modern classes are defined in .m files where the filename matches the class name. The definition starts with the classdef keyword.
Let’s create a practical BankAccount class to illustrate key features. Create a file named BankAccount.m.
% BankAccount.mclassdef BankAccount < handle % A handle class representing a simple bank account.
properties (Access = public) AccountHolder string end
properties (SetAccess = private) % Can be read from outside, but only set internally. AccountNumber (1,1) double Balance (1,1) double = 0.0 end
properties (Constant) % A constant property shared by all instances. BankName string = "MATLAB Central Bank" end
methods % --- Constructor Method --- function obj = BankAccount(holderName, initialDeposit) % Creates an instance of the BankAccount class. arguments holderName (1,1) string initialDeposit (1,1) double {mustBeNonnegative} = 0 end
obj.AccountHolder = holderName; obj.Balance = initialDeposit;
% Assign a unique account number (simple example) obj.AccountNumber = randi([1e5, 1e6-1]);
fprintf('Welcome, %s! Account #%d created with a balance of $%.2f.\n', ... obj.AccountHolder, obj.AccountNumber, obj.Balance); end
% --- Public Methods --- function deposit(obj, amount) % Deposits money into the account. arguments obj BankAccount amount (1,1) double {mustBePositive} end obj.Balance = obj.Balance + amount; fprintf('Deposited $%.2f. New balance: $%.2f.\n', amount, obj.Balance); end
function withdraw(obj, amount) % Withdraws money from the account. arguments obj BankAccount amount (1,1) double {mustBePositive} end
if amount > obj.Balance error('BankAccount:InsufficientFunds', ... 'Withdrawal amount of $%.2f exceeds current balance of $%.2f.', ... amount, obj.Balance); end
obj.Balance = obj.Balance - amount; fprintf('Withdrew $%.2f. New balance: $%.2f.\n', amount, obj.Balance); end endendKey Features Explained
Section titled “Key Features Explained”classdef BankAccount < handle: This defines a class namedBankAccountthat inherits fromhandle. Handle classes behave like references; when you copy a handle object, you are copying the reference, not the object’s data. Both copies point to the same underlying data. This is different from the default value classes, where copying creates a completely independent duplicate.properties (Attribute): Property blocks are used to define the data. Attributes control their behavior:-
- **`Access = public`**: Can be read and written from anywhere (e.g., `AccountHolder`).
-
- **`SetAccess = private`**: Can be read from anywhere, but only modified by methods within the class (e.g., `Balance`, `AccountNumber`). This is a key part of encapsulation.
-
- **`Constant`**: The value is fixed and cannot be changed (e.g., `BankName`).
methods: Methods blocks contain the functions that operate on the object. The first argument to any non-static method is always the object itself (conventionally namedobj).- Constructor (
BankAccount(...)): A special method with the same name as the class. It is called automatically when you create an object (e.g.,myAccount = BankAccount(...)). argumentsblock: A modern and highly recommended feature for validating inputs to your methods, making your code more robust and self-documenting.
Using the Class
Section titled “Using the Class”You can now create and interact with BankAccount objects from the MATLAB Command Window or a script.
% Create two accountsaccount1 = BankAccount("Alice", 200.0);Welcome, Alice! Account #157363 created with a balance of $200.00.
account2 = BankAccount("Bob");Welcome, Bob! Account #935069 created with a balance of $0.00.
% Perform operationsaccount1.deposit(50.0);Deposited $50.00. New balance: $250.00.
account2.deposit(1000.0);Deposited $1000.00. New balance: $1000.00.
account1.withdraw(30.0);Withdrew $30.00. New balance: $220.00.
% Trying to modify a private-set property will failaccount1.Balance = 5000;Error using BankAccount/set.BalanceYou cannot set the read-only property 'Balance' of BankAccount.
% Trying an invalid operationaccount1.withdraw(300.0);Error using BankAccount/withdraw (line 69)Withdrawal amount of $300.00 exceeds current balance of $220.00.Essential Built-in Functions for OOP
Section titled “Essential Built-in Functions for OOP”MATLAB provides functions to inspect and work with objects at runtime.
class(obj): Get the Class Name
Section titled “class(obj): Get the Class Name”The class function returns the class name of a variable as a string. This is useful for type-checking.
myAccount = BankAccount("Charlie");Welcome, Charlie! Account #489764 created with a balance of $0.00.
className = class(myAccount)className = "BankAccount"
someNumber = 42;class(someNumber)ans = 'double'isobject(A): Check if a Variable is an Object
Section titled “isobject(A): Check if a Variable is an Object”The isobject function returns logical true if the input variable is an instance of any MATLAB class, and false otherwise.
isobject(myAccount)ans = logical 1
myStruct = struct('field', 'value');isobject(myStruct)ans = logical 0isa(obj, 'ClassName'): Check for Specific Class Type
Section titled “isa(obj, 'ClassName'): Check for Specific Class Type”The isa function is more specific than isobject. It returns true if an object is an instance of a specified class or any of its subclasses. This is the preferred way to check an object’s type.
isa(myAccount, 'BankAccount')ans = logical 1
isa(myAccount, 'handle') % BankAccount inherits from handleans = logical 1
isa(myAccount, 'double')ans = logical 0Next Steps and Best Practices
Section titled “Next Steps and Best Practices”- Testing: Use the MATLAB Unit Testing Framework to write automated tests for your classes. This ensures your methods work as expected and prevents regressions.
- Packages: For larger projects, organize related classes into packages (folders starting with
+). This prevents name conflicts and groups functionality, e.g.,+mybank/BankAccount.m. - Static Methods: Define methods that belong to the class but not to a specific instance using the
Staticattribute. They are useful for utility functions related to the class. - Events and Listeners: Implement the observer design pattern by defining events in your class and creating listeners that react when those events are triggered.