MATLAB Object-Oriented Programming (OOP)
Introduction to object-oriented programming in MATLAB including classes, properties, methods, constructors, inheritance, encapsulation, and practical examples.
MatLab Programming
Functions
Single Output function
function out =fnName(param1, param2...)
...body
end
Multi Output function
function [out1, out2, ..] =fnName(param1, param 2...)
...body
end
eg:
function y = squareThisNumber(x)
y= x^2
// Multiple Output
function [y1,y2] = squareAndCubeThisNumber(x)
y1= x^2
y2= x^3
Anonymous function
-
Returns only single output
-
Can be pass as input to other function
-
f is called Function Handle
f = @(params..) expression
Classes
A MATLAB class lives in its own file, named after the class, starting with classdef.
% File: Point.m
classdef Point
properties
x
y
end
methods
% Constructor β same name as the class
function obj = Point(x, y)
obj.x = x;
obj.y = y;
end
function d = distanceFromOrigin(obj)
d = sqrt(obj.x^2 + obj.y^2);
end
end
end
Usage:
p = Point(3, 4);
p.distanceFromOrigin() % 5
Properties
Hold the state/data of an object β equivalent to fields/attributes in other OOP languages.
properties
x
y = 0 % default value
end
properties (Access = private)
secret % only accessible inside the class
end
Methods
Functions that operate on an object's properties. The first argument is conventionally
obj.
methods
function obj = setX(obj, newX)
obj.x = newX; % MATLAB objects are value types β must return obj
end
end
Constructor
A method with the same name as the class, called automatically when you create an instance (
Point(3,4)). If omitted, MATLAB provides a default constructor that takes no arguments.
Inheritance
A subclass extends a base class using
< BaseClassName, reusing its properties/methods and overriding what it needs to.
classdef Point3D < Point
properties
z
end
methods
function obj = Point3D(x, y, z)
obj = obj@Point(x, y); % call superclass constructor
obj.z = z;
end
function d = distanceFromOrigin(obj)
d = sqrt(obj.x^2 + obj.y^2 + obj.z^2); % overrides Point's method
end
end
end
Encapsulation
Restrict direct access to internal state using
Accessattributes on properties/methods, exposing only what callers need.
properties (Access = private)
balance = 0
end
methods
function obj = deposit(obj, amount)
obj.balance = obj.balance + amount;
end
function b = getBalance(obj)
b = obj.balance; % controlled read access, no direct external writes
end
end
