
- MATLAB - Home
- MATLAB - Overview
- MATLAB - Features
- MATLAB - Environment Setup
- MATLAB - Editors
- MATLAB - Online
- MATLAB - Workspace
- MATLAB - Syntax
- MATLAB - Variables
- MATLAB - Commands
- MATLAB - Data Types
- MATLAB - Operators
- MATLAB - Dates and Time
- MATLAB - Numbers
- MATLAB - Random Numbers
- MATLAB - Strings and Characters
- MATLAB - Text Formatting
- MATLAB - Timetables
- MATLAB - M-Files
- MATLAB - Colon Notation
- MATLAB - Data Import
- MATLAB - Data Output
- MATLAB - Normalize Data
- MATLAB - Predefined Variables
- MATLAB - Decision Making
- MATLAB - Decisions
- MATLAB - If End Statement
- MATLAB - If Else Statement
- MATLAB - If…Elseif Else Statement
- MATLAB - Nest If Statememt
- MATLAB - Switch Statement
- MATLAB - Nested Switch
- MATLAB - Loops
- MATLAB - Loops
- MATLAB - For Loop
- MATLAB - While Loop
- MATLAB - Nested Loops
- MATLAB - Break Statement
- MATLAB - Continue Statement
- MATLAB - End Statement
- MATLAB - Arrays
- MATLAB - Arrays
- MATLAB - Vectors
- MATLAB - Transpose Operator
- MATLAB - Array Indexing
- MATLAB - Multi-Dimensional Array
- MATLAB - Compatible Arrays
- MATLAB - Categorical Arrays
- MATLAB - Cell Arrays
- MATLAB - Matrix
- MATLAB - Sparse Matrix
- MATLAB - Tables
- MATLAB - Structures
- MATLAB - Array Multiplication
- MATLAB - Array Division
- MATLAB - Array Functions
- MATLAB - Functions
- MATLAB - Functions
- MATLAB - Function Arguments
- MATLAB - Anonymous Functions
- MATLAB - Nested Functions
- MATLAB - Return Statement
- MATLAB - Void Function
- MATLAB - Local Functions
- MATLAB - Global Variables
- MATLAB - Function Handles
- MATLAB - Filter Function
- MATLAB - Factorial
- MATLAB - Private Functions
- MATLAB - Sub-functions
- MATLAB - Recursive Functions
- MATLAB - Function Precedence Order
- MATLAB - Map Function
- MATLAB - Mean Function
- MATLAB - End Function
- MATLAB - Error Handling
- MATLAB - Error Handling
- MATLAB - Try...Catch statement
- MATLAB - Debugging
- MATLAB - Plotting
- MATLAB - Plotting
- MATLAB - Plot Arrays
- MATLAB - Plot Vectors
- MATLAB - Bar Graph
- MATLAB - Histograms
- MATLAB - Graphics
- MATLAB - 2D Line Plot
- MATLAB - 3D Plots
- MATLAB - Formatting a Plot
- MATLAB - Logarithmic Axes Plots
- MATLAB - Plotting Error Bars
- MATLAB - Plot a 3D Contour
- MATLAB - Polar Plots
- MATLAB - Scatter Plots
- MATLAB - Plot Expression or Function
- MATLAB - Draw Rectangle
- MATLAB - Plot Spectrogram
- MATLAB - Plot Mesh Surface
- MATLAB - Plot Sine Wave
- MATLAB - Interpolation
- MATLAB - Interpolation
- MATLAB - Linear Interpolation
- MATLAB - 2D Array Interpolation
- MATLAB - 3D Array Interpolation
- MATLAB - Polynomials
- MATLAB - Polynomials
- MATLAB - Polynomial Addition
- MATLAB - Polynomial Multiplication
- MATLAB - Polynomial Division
- MATLAB - Derivatives of Polynomials
- MATLAB - Transformation
- MATLAB - Transforms
- MATLAB - Laplace Transform
- MATLAB - Laplacian Filter
- MATLAB - Laplacian of Gaussian Filter
- MATLAB - Inverse Fourier transform
- MATLAB - Fourier Transform
- MATLAB - Fast Fourier Transform
- MATLAB - 2-D Inverse Cosine Transform
- MATLAB - Add Legend to Axes
- MATLAB - Object Oriented
- MATLAB - Object Oriented Programming
- MATLAB - Classes and Object
- MATLAB - Functions Overloading
- MATLAB - Operator Overloading
- MATLAB - User-Defined Classes
- MATLAB - Copy Objects
- MATLAB - Algebra
- MATLAB - Linear Algebra
- MATLAB - Gauss Elimination
- MATLAB - Gauss-Jordan Elimination
- MATLAB - Reduced Row Echelon Form
- MATLAB - Eigenvalues and Eigenvectors
- MATLAB - Integration
- MATLAB - Integration
- MATLAB - Double Integral
- MATLAB - Trapezoidal Rule
- MATLAB - Simpson's Rule
- MATLAB - Miscellenous
- MATLAB - Calculus
- MATLAB - Differential
- MATLAB - Inverse of Matrix
- MATLAB - GNU Octave
- MATLAB - Simulink
MATLAB - User-Defined Classes
MATLAB is traditionally known for its powerful matrix operations and built-in functions, but it also supports object-oriented programming (OOP). User-defined classes in MATLAB allow you to create custom data types that encapsulate data and functions (methods) that operate on that data. This approach can help organize code, promote reusability, and model complex systems more naturally.
What is a Class?
A class is a blueprint for creating objects (instances). It defines properties (data) and methods (functions) that the objects created from the class will have.
Defining a Class
In MATLAB, you define a class using the classdef keyword. Heres a simple example −
classdef MyClass properties Property1 end methods function obj = MyClass(val) if nargin > 0 obj.Property1 = val; end end function output = myMethod(obj, input) output = obj.Property1 + input; end end end
Breakdown of the Example
1. Class Definition
classdef MyClass
This line declares a new class named MyClass.
2. Properties Block
properties Property1 end
Properties are variables that hold data for objects of the class. In this example, MyClass has one property, Property1.
3. Methods Block
methods
Methods are functions that define the behavior of the class. They operate on objects of the class.
4. Constructor Method
function obj = MyClass(val) if nargin > 0 obj.Property1 = val; end end
The constructor method is a special function that MATLAB calls when creating a new object. The name of the constructor method is the same as the class name. Here, the constructor initializes Property1 if an input value val is provided.
5. Other Methods
function output = myMethod(obj, input) output = obj.Property1 + input; end
This is a regular method named myMethod. It takes two inputs: obj (the object itself) and input. It returns the sum of Property1 and input.
Creating Objects
To create an object of MyClass, you use the constructor method:
obj = MyClass(10); disp(obj.Property1); % Here Output: 10
Using Methods
You can call methods on an object using dot notation
result = obj.myMethod(5); disp(result); % Here Output: 15
Advantages of Using Classes
- Encapsulation − Group related data and functions together, making the code more modular and easier to manage.
- Reusability − Once a class is defined, it can be reused in different parts of a project or in different projects.
- Abstraction − Hide the internal implementation details and expose only the necessary interface.
- Inheritance − Create new classes that inherit properties and methods from existing classes, promoting code reuse and hierarchical class structures.
Example 1: A Point Class
Heres a more practical example, defining a class to represent a 2D point.
classdef Point properties X Y end methods function obj = Point(x, y) if nargin > 0 obj.X = x; obj.Y = y; end end function obj = set.X(obj, x) if x >= 0 obj.X = x; else error('X must be non-negative'); end end function obj = set.Y(obj, y) if y >= 0 obj.Y = y; else error('Y must be non-negative'); end end function distance = distanceToOrigin(obj) distance = sqrt(obj.X^2 + obj.Y^2); end end end
Using the Point Class
p = Point(3, 4); disp(p.X); % Output: 3 disp(p.Y); % Output: 4 dist = p.distanceToOrigin(); disp(dist); % Output: 5
In this example −
- The Point class has properties X and Y to store coordinates.
- The constructor initializes these properties.
- Set methods (set.X and set.Y) validate that coordinates are non-negative.
- The distanceToOrigin method calculates the Euclidean distance from the origin to the point.
Example 2: A Circle Class
This class will include properties for the radius and center of the circle, and methods to calculate the area, circumference, and to check if a point is inside the circle.
Circle Class Definition
classdef Circle properties Radius Center end methods % Constructor function obj = Circle(radius, center) if nargin > 0 obj.Radius = radius; obj.Center = center; end end % Method to calculate area function area = area(obj) area = pi * obj.Radius^2; end % Method to calculate circumference function circumference = circumference(obj) circumference = 2 * pi * obj.Radius; end % Method to check if a point is inside the circle function isIn = isPointInside(obj, point) distance = sqrt((point(1) - obj.Center(1))^2 + (point(2) - obj.Center(2))^2); isIn = distance <= obj.Radius; end end end
Breakdown of the Circle Class
1. Class Definition
classdef Circle
2. Properties
properties Radius Center end
The Circle class has two properties: Radius (the radius of the circle) and Center (a 2-element vector representing the x and y coordinates of the circle's center).
3. Constructor Method
function obj = Circle(radius, center) if nargin > 0 obj.Radius = radius; obj.Center = center; end end
The constructor initializes the Radius and Center properties if input arguments are provided.
4. Area Method
function area = area(obj) area = pi * obj.Radius^2; end
This method calculates the area of the circle using the formula x Radius2
5. Circumference Method
function circumference = circumference(obj) circumference = 2 * pi * obj.Radius; end
This method calculates the circumference of the circle using the formula 2 x x Radius.
6. Point Inside Check Method.
function isIn = isPointInside(obj, point) distance = sqrt((point(1) - obj.Center(1))^2 + (point(2) - obj.Center(2))^2); isIn = distance <= obj.Radius; end
This method checks if a given point is inside the circle. It calculates the distance from the point to the center of the circle and checks if this distance is less than or equal to the radius.
Using the Circle Class
To create a Circle object and use its methods, you can do the following.
% Create a Circle object with radius 5 and center at (0, 0) c = Circle(5, [0, 0]); % Calculate the area a = c.area(); disp(['Area: ', num2str(a)]); % Output: Area: 78.5398 % Calculate the circumference circ = c.circumference(); disp(['Circumference: ', num2str(circ)]); % Output: Circumference: 31.4159 % Check if a point is inside the circle point = [3, 4]; isInside = c.isPointInside(point); disp(['Is the point inside the circle? ', num2str(isInside)]); % Output: Is the point inside the circle? 1 % Check if another point is inside the circle point = [6, 0]; isInside = c.isPointInside(point); disp(['Is the point inside the circle? ', num2str(isInside)]); % Output: Is the point inside the circle? 0