Types of Functions in MATLAB Explained With Examples (2025)
By Mukesh Kumar
Updated on Apr 22, 2025 | 27 min read | 1.5k views
Share:
For working professionals
For fresh graduates
More
By Mukesh Kumar
Updated on Apr 22, 2025 | 27 min read | 1.5k views
Share:
Table of Contents
The types of functions in MATLAB are fundamental to its proficiency in performing high-speed mathematical operations and matrix manipulations. Unlike other programming languages that process individual elements separately, MATLAB's matrix-first approach allows it to handle entire arrays as single entities. This design enormously improves computational efficiency and reduces code complexity. It accelerates data analysis, scientific computing, and engineering applications.
Understanding the different types of functions in MATLAB, including built-in, user-defined, anonymous, nested, and function handles, encourages users to optimize performance and write more efficient code for technical and research-based tasks.
This guide walks through each function type with clear examples from real-world scenarios. You will learn how to choose the right function type for your task and combine them to solve complex problems.
The types of functions in MATLAB include pre-programmed functions that perform calculations without writing new code. The built-in functions of MATLAB compute everything from basic arithmetic to mathematical operations.
MATLAB’s functions are not to be confused with MATLAB scripts. When it comes to script vs function, the script runs a sequence of commands in order from top to bottom. The function takes specific inputs, processes them according to defined steps, and returns outputs.
These functions help engineers, scientists, and researchers process data, analyze signals, and solve mathematical problems without writing code from scratch. Let us discuss the built-in types of functions of MATLAB in detail:
MATLAB's core mathematical applications and functions serve as important tools for numerical computing. Let us have a detailed look at these functions:
This function calculates the principal square root of a number and works for both real and complex numbers. The sqrt() function helps calculate distances, analyse exponential growth, and solve quadratic equations.
The sin() function computes the trigonometric sine of angles. MATLAB expects angle inputs in radians. This makes it useful for signal processing, wave analysis, and geometric calculations. Engineers often use this function to model periodic phenomena like sound waves or electrical signals.
The fft() function converts data from the time domain to the frequency domain. This transformation reveals the frequency components present in a signal. Signal processing engineers use fft() to analyze audio signals, design filters, and process images.
Here's how these functions work in practice:
x = 16;
result1 = sqrt(x); % Computes the square root of 16, returns 4
result2 = sin(pi/4); % Calculates sine of pi/4 radians (45 degrees)
result3 = fft([1, 2, 3, 4]); % Transforms array into frequency components
Each function accepts specific input types.
MATLAB optimizes these functions for performance. They execute faster than equivalent user-written code because they use specialized algorithms and hardware. This optimization becomes important when processing large datasets or performing repeated calculations in simulations.
MATLAB's plotting functions transform raw data into meaningful visual representations. These types of functions in MATLAB are:
The plot() creates two-dimensional line graphs by connecting data points with lines. When you provide two sets of numbers (x and y coordinates), this function draws lines between these points. Take the example of tracking temperature changes throughout the day. In this, plot() can show how temperature varies with time.
It displays individual data points without connecting lines. This further helps reveal patterns and clusters in datasets. This MATLAB function works well for showing data distributions, like plotting heights versus weights of different people to look for patterns.
For three-dimensional data, the surf() function creates surface plots. The surf() shows how one value (height) changes based on two other values (x and y positions).
Let us examine this code that demonstrates basic plotting:
%Creating a sine wave visualization
x = 0:0.1:10; %Generate x values from 0 to 10 in steps of 0.1
y = sin(x); %Calculate sine values for each x
plot(x, y); % Create the 2D plot
xlabel('X-axis'); % Label for x-axis
ylabel('Y-axis'); % Label for y-axis
title('Sine Wave'); % Title for the plot
%Creating a 3D surface plot
[X, Y] = meshgrid(-3:0.1:3, -3:0.1:3); %Create grid of x,y coordinates
Z = X.^2 + Y.^2; %Calculate z value for each point
surf(X, Y, Z); %Generate 3D surface plot
In the first example, the code creates a sine wave visualization. The ‘0:0.1:10’ MATLAB function syntax generates numbers from 0 to 10 in steps of 0.1. The plot() function then draws lines between these points, creating a smooth wave pattern. The labels help readers understand what the graph represents.
The second example shows how to create a three-dimensional surface plot. The meshgrid() function creates two matrices that together define a grid of points. The formula X.^2 + Y.^2 calculates the height (Z) at each point. The result resembles a bowl-shaped surface that opens upward.
Also Read: K Means Clustering Matlab [With Source Code]
MATLAB toolboxes help programmers work on specialized tasks. Let us explore two important toolboxes in MATLAB:
1. The Image Processing Toolbox
This MATLAB toolbox helps you work with digital images. The imread() function reads image files into MATLAB's memory. It understands many image formats (JPG, PNG, TIFF) and converts them into matrices of numbers. Each number represents one pixel's brightness or color. For example:
The imshow() function displays these matrices as visible images on your screen. It automatically scales the brightness values and handles color conversion. Here's how to work with images in MATLAB:
img = imread('example.jpg'); %Load the image file into memory
imshow(img); %Display the loaded image
This code reads an image file named 'example.jpg' from your computer. The imread() function converts the image into a matrix of numbers that represent pixel values. The imshow() function then converts these numbers back into a visible image on your screen.
2. The Control System Toolbox
This MATLAB toolbox serves engineers who design control systems. The tf() function creates transfer functions. These are mathematical models that describe how systems respond to inputs. Engineers use these to model things like:
Engineers use bode() plots to understand system behavior at different frequencies, which helps them design stable control systems. This helps engineers:
Ready to kickstart your data engineering journey as a professional? Explore upGrad’s Data Analysis Courses to benefit from in-depth modules and live learning sessions.
Apart from MATLAB’s built-in functions, it also lets you create your own functions to solve specific problems. These are user-defined functions to help you write reusable code that performs custom operations. These accept inputs, process them according to your instructions and return the results. They organize code into manageable pieces and make programs easier to understand. Let us discuss the user-defined types of functions in MATLAB:
A MATLAB user-defined function consists of several key components that work together. The function definition starts with the 'function' keyword, followed by output and input parameters. The function body contains the actual code that processes the inputs. The 'end' statement marks where the function stops.
Let us examine a simple function that squares a number:
function output = squareNumber(input)
output = input^2;
end
This code creates a function named 'squareNumber'. Let us break down each part:
To use this function, you must save it in a file named 'squareNumber.m'. The filename must match the function name exactly. Then you can call it like this:
result = squareNumber(4);
When you run this code, MATLAB:
This example shows a simple function. It is also possible to create complex functions that perform:
Each function should focus on one specific task to keep your code organized and easy to understand.
The various types of functions in MATLAB excel at processing multiple pieces of information simultaneously. Let us explore how functions handle different numbers of input/output arguments:
These tools help create versatile functions that adapt to different needs. Given below is a function that performs basic math operations:
function [sum, product] = mathOps(a, b)
sum = a + b; %Add the two numbers
product = a * b; %Multiply the two numbers
end
This function showcases multiple input and output handling. Let us break down how it works:
Inside the function, two calculations occur:
When you call the function:
[x, y] = mathOps(4, 5); % x = 9, y = 20
The function processes inputs 4 and 5, performs both calculations, and returns two values. The first value (9) goes into x, and the second value (20) goes into y.
MATLAB offers tools to find and fix problems in your functions. The debugging process helps you understand how your code executes and where issues might occur.
The dbstop command sets points where your code pauses during execution. This pause lets you examine variable values and program flow. Here is how you can implement it:
dbstop if error %Pause when MATLAB encounters an error
dbstop in myFunction 10 %Pause at line 10 in myFunction
%Other debugging commands:
dbstep %Execute the next line of code
dbcont %Continue running until the next stop
dbquit %Exit debug mode and stop the program
These debugging functions and tools work together to help you investigate your code:
For example, if your function produces unexpected results, you can:
This systematic approach helps identify and correct issues in your functions efficiently.
Explore the world of Machine Learning and Artificial Intelligence with upGrad’s Online Artificial Intelligence and Machine Learning Programs. Start your AI-driven programming career today!
Anonymous functions offer a way to create small, single-purpose functions without creating separate files. They work similarly to mathematical expressions you can name and reuse. These functions live directly in your code and excel at simple calculations that you might need multiple times. Their compact nature makes them perfect for data analysis and mathematical operations. Let us learn more about anonymous types of functions in MATLAB:
Anonymous functions in MATLAB follow a specific structure that sets them apart from regular functions. The ‘@’ symbol tells MATLAB that it is creating a function handle or a reference that lets it use the function like a variable. The parentheses after @ hold the input names, and the expression after tells MATLAB what to do with those inputs. Consider this example:
matlabCopyf = @(x) x^2 + 3*x; % Create the anonymous function
result = f(5); % Use the function with input 5
This code creates a mathematical function that works with any number. Let us break down each part:
When we call f(5), MATLAB:
Anonymous functions prove useful when you are working with mathematical formulas that you will use repeatedly. They help in passing functions as arguments to other functions and creating quick data transformations. Anonymous functions in MATLAB define custom criteria for sorting or filtering. For instance, you can use an anonymous function to convert temperatures:
matlabCopycelsius_to_fahrenheit = @(c) (c * 9/5) + 32;
fahrenheit = celsius_to_fahrenheit(20); % Converts 20°C to 68°
Anonymous functions serve a specific purpose in MATLAB, but they come with important restrictions that shape how we use them. Knowledge of these limitations helps you decide when to use anonymous functions and when to create traditional functions instead.
The key limitation lies in expression complexity. Anonymous functions must complete their work in a single line of code. They cannot contain loops, multiple calculations in sequence, or conditional statements. Think of them like simple mathematical formulas rather than full programs. Given below is the difference between the incorrect and correct approaches:
% INCORRECT: This will cause an error
f = @(x) disp(x); x^2; % Tries to do two things:
% 1. Display the value
% 2. Calculate square
% MATLAB cannot handle multiple statements
% CORRECT: Use a regular function instead
function y = myFunction(x) % Create standard function
y = x^2; % Calculate square
disp(y); % Display result
end % End function definition
The incorrect version fails because it attempts two separate operations. MATLAB's anonymous function syntax cannot handle the semicolon that separates these commands. Consider these practical examples of when to use each type:
square = @(x) x^2; % Simple math operation
celsiusToKelvin = @(c) c + 273.15; % Single conversion
areaCircle = @(r) pi * r^2; % Basic geometric formula
function result = processList(numbers)
result = 0;
for i = 1:length(numbers) % Loop requires regular function
result = result + numbers(i);
end
disp(['Sum: ' num2str(result)]); % Multiple operations need
end % regular function structure
This knowledge helps you choose the right tool for each task. Use anonymous functions for quick, single-line calculations. Switch to regular functions when you need more complex logic, multiple steps, or data display operations.
Are you on a budget but want to learn in-demand skills and technology for upskilling? Explore upGrad’s free certification courses that include cutting-edge learning programs free of cost!
MATLAB allows functions to contain other functions inside them, creating a hierarchy of related code. These nested functions help organize complex operations into smaller, manageable pieces. They share access to variables, which reduces the need to pass data between functions. Let us learn more about these types of functions in MATLAB:
Nested functions live inside other functions, giving them unique capabilities. They can see and use variables from their parent function without needing those variables to be passed directly to them. This shared access to data makes nested functions particularly useful when several operations need to work with the same information. Consider a simple example:
function mainFunction
a = 10; % Create variable in parent function
nestedFunction(); % Call the nested function
function nestedFunction
disp(a); % Display value of 'a' from parent
end
end
This code demonstrates how nested functions work. Let us break down each part:
1. The parent function ‘mainFunction’:
2. The nested function ‘nestedFunction’:
Below is a more practical example showing why nested functions prove useful:
function processData(data)
total = 0; % Variable available to all nested functions
function sumValues
total = sum(data); % Update shared variable
end
function calculateAverage
average = total / length(data);
disp(['Average: ' num2str(average)]);
end
sumValues(); % Call first nested function
calculateAverage(); % Call second nested function
end
This structure offers several benefits:
MATLAB files can contain multiple functions, with one main function and several supporting subfunctions. These subfunctions work like specialized tools that help the main function complete its tasks. You can only call these subfunctions from within the same file where you defined them.
Subfunctions work like private assistants to the main function. They stay hidden from the outside world and only respond to calls from their main function. This makes them perfect for breaking down complex operations into smaller, manageable pieces. Let us look at a practical example:
function mainFunction
y = helperFunction(5);
disp(y);
end
function out = helperFunction(x)
out = x * 2;
end
In this code, ‘mainFunction’ serves as our primary function. It is called ‘helperFunction’, which multiplies its input by 2. When we run mainFunction, it sends the value 5 to helperFunction, receives 10 in return, and displays this result. The key points about subfunctions include:
Variable scope helps you manage data flow between functions in MATLAB. The scope determines which functions can access specific variables and how they share information. MATLAB handles variable access differently for nested functions and subfunctions. Let us analyze both:
function parentFunction
a = 5; % Parent variable
function nestedFunction
disp(a); % Nested function can see 'a'
end
end
% In a different case with subfunctions:
function main
a = 5;
subFunction(a); % Must pass 'a' explicitly
end
function subFunction(x)
disp(x); % Subfunction only sees what you pass to it
end
When you create a variable in parentFunction, any nested function inside it can read and modify that variable. Subfunctions work more like independent neighbors. They need you to hand them any information they should use explicitly. This separation helps prevent accidental changes to variables and makes the code's data flow more predictable.
This difference in variable access reflects two distinct MATLAB programming approaches:
Harness the power of new technology to scale your programming career. Check out upGrad’s Fundamentals of Deep Learning and Neural Networks free certification course today!
MATLAB’s function handles let you reference functions directly in your code. They allow you to pass functions as arguments to other functions or store them in variables. This capability opens up many possibilities for flexible and reusable code. It is useful when working with callback functions in graphical interfaces or optimization problems. Let us learn more about function handles and callbacks in MATLAB:
Function handles provide a direct link to functions in MATLAB. When you create a function handle, you tell MATLAB to keep track of a specific function that you want to use later. The @ symbol creates this link, much like a bookmark that points to a particular function. Here is how a function works in practice:
% Create a function handle for the sine function
f = @sin;
% Use the function handle to calculate sine of pi/2
result = f(pi/2); % Returns 1
% Create a handle for a custom multiplication function
multiply = @(x,y) x * y;
product = multiply(4,5); % Returns 20
Function handles become useful when you need to:
You can create function handles in several ways:
sqrt_handle = @sqrt;
my_func_handle = @my_function;
cube = @(x) x^3;
The function handles are very beneficial when you use them with higher-order functions. These functions take other functions as inputs. For example, MATLAB's integration function integral accepts a function handle:
area = integral(@sin, 0, pi);
Each function handle maintains its own workspace and variables. This means you can create multiple handles that use the same function but with different preset values:
double = @(x) 2 * x;
triple = @(x) 3 * x;
result1 = double(5); % Returns 10
result2 = triple(5); % Returns 15
Function handles form the foundation of interactive MATLAB applications. They connect user actions like button clicks to the code that responds to those actions. A Graphic User Interface (GUI) creates a visual way for users to interact with software through elements like buttons, sliders, and text boxes. Instead of typing commands, users can click, drag, or enter values to make things happen. You can refer to our GUI Tutorial to learn more about its components and role in software design.
Event-driven programming responds to user actions (events) rather than following a fixed sequence. The program waits for the user to do something and then responds accordingly. This is how a function handles connecting these concepts in MATLAB:
% Create a window for our GUI
figure('Name', 'Simple Calculator');
% Create a button that users can click
btn = uicontrol('Style', 'pushbutton', ...
'String', 'Click Me', ...
'Position', [50 50 100 30]);
% Connect the button to its response function
btn.Callback = @buttonCallback;
% Define what happens when someone clicks
function buttonCallback(~, ~)
disp('Button clicked!');
end
Let us break down what happens in this code:
In MATLAB's App Designer, this same principle applies but with more sophisticated tools. App Designer lets you drag and drop GUI elements and automatically creates the framework for handling events. You still use function handles to define what happens when users interact with these elements.
This approach makes programs more interactive and user-friendly. Instead of running straight through from start to finish, the program stays ready to respond to whatever the user decides to do next. Function handles make this possible by creating clear connections between user actions and program responses.
Want to automate and innovate your programming projects and systems? Explore upGrad’s Online Software Development Courses that integrate cutting-edge technology to help you stay ahead!
Writing effective MATLAB functions requires more than just getting the right output. The way you structure your code affects how fast it runs and how understandable it is for others. Following established best MATLAB coding practices helps you create functions that run efficiently. You can also maintain them as your projects grow. Here are the best practices that you must follow for MATLAB functions:
MATLAB excels at handling arrays and matrices as single units rather than processing individual elements one by one. Understanding this fundamental principle helps you write faster code by leveraging MATLAB's strengths.
Consider this comparison of two approaches for creating an array of squared numbers:
% Method 1: Using a loop (slower)
tic % Start timing
for i = 1:10000
A(i) = i^2;
end
toc % Display elapsed time
% Method 2: Using vectorization (faster)
tic % Start timing
A = (1:10000).^2;
toc % Display elapsed time
Loops can slow down your programs because they handle one piece of data at a time. It is like counting beans one by one, instead of weighing the whole bag. The second method runs much faster because it uses vectorization. Instead of calculating each square one at a time, MATLAB processes all numbers simultaneously. It works like giving instructions to a group. It is faster to tell everyone what to do at once rather than repeating the same instruction for each person.
When you know how big your arrays will be, telling MATLAB in advance through pre-allocation helps save time. Built-in vectorized operations in MATLAB let you perform calculations on entire arrays simultaneously. For example, instead of adding numbers one at a time in a loop, vectorization adds all the numbers at once. This approach takes advantage of MATLAB's core strengths and leads to faster, cleaner code.
These optimization techniques are important when processing large datasets or running simulations where every millisecond counts
Also Read: While loop in MATLAB: Everything You Need to Know
Good documentation helps other programmers understand and use your code. When you write clear comments and choose meaningful names, you make your code easier to maintain and update over time. This becomes important when working on team projects or when you need to revisit your own code months later. Consider this well-documented function:
function area = circleArea(radius)
area = pi * radius^2;
end
Here, circleArea calculates the area of a circle
area = circleArea(radius) computes the area using pi * radius^2
radius - The radius of the circle (must be positive)
area - The calculated area of the circle
area = circleArea(5)
returns 78.5398
Programs should handle unexpected situations gracefully. Good error handling prevents crashes and helps users understand what went wrong. MATLAB provides several tools to manage errors effectively. Here is an example of error handling:
function result = safeDivide(a, b)
try
result = a / b;
catch
disp('Error: Division by zero.');
result = NaN;
end
end
This example shows several error-handling best practices:
When you use this function, it handles problems smoothly:
x = safeDivide(10, 0) % Returns Inf with a warning
x = safeDivide('text', 5) % Returns error about invalid input
Want to learn how MATLAB can optimize financial modeling and data analysis? Check out upGrad’s free course on Digital Innovations in the Financial System to learn MATLAB’s application in the finance sector.
upGrad's software and technology programs connect academic learning with real industry requirements. Our courses teach you both the fundamentals and advanced concepts through hands-on MATLAB projects and practical assignments. Here is how you can benefit from upGrad’s learning platform to master one of the highest-paying programming languages in 2025:
upGrad's certification programs and training courses give you skills that match current industry needs. The program structure is created by obtaining input from leading technology companies and experienced practitioners. You learn through real-world case studies and projects that mirror actual workplace challenges. Our certification program includes:
Here are upGrad’s top software and technology, data science, and AI/ML courses where you can learn about applying MATLAB coding skills:
upGrad Online Courses |
Duration |
Course Inclusions |
Executive Diploma in Machine Learning and AI with IIIT-B |
13 months |
|
Post Graduate Certificate in Machine Learning & NLP (Executive) |
8 Months |
|
8 Months |
|
|
Executive Diploma in Data Science & AI with IIIT-B |
12 months |
|
Professional Certificate Program in Cloud Computing and DevOps |
8 Months |
|
At upGrad, you learn directly from professionals who use MATLAB in their daily work. Our mentors come from diverse technology backgrounds and share practical insights from their experience. The mentorship program provides:
When you join upGrad’s network of learners, you connect with alumni who work at major technology companies. You also get access to upGrad’s placement support. These connections often lead to referrals and job opportunities. Our alumni network spans companies like TCS, Infosys, Microsoft, and Sabre.
upGrad helps you prepare for your career move through structured support programs. We work with you from resume creation to interview preparation. Our career support includes:
Companies trust upGrad graduates because they demonstrate both technical knowledge and practical problem-solving abilities. Our placement partnerships include leading technology firms, research organizations, and engineering companies. Still confused about how to make a career switch? You can visit a nearby upGrad’s offline experience and learning support center to get personalized counseling sessions on your career needs.
Also Read: Data Science for Beginners: Prerequisites, Learning Path, Career Opportunities and More
The types of functions in MATLAB provide powerful tools for solving technical challenges with efficiency and precision. Each function type plays an important role in optimizing performance and simplifying complex computations.
Built-in functions handle fundamental mathematical operations, facilitating quick calculations without writing additional code. User-defined functions allow for custom solutions tailored to specific problems, enhancing code reusability.
Anonymous functions streamline short, one-line computations without the need for separate files, making them ideal for quick mathematical operations. Nested and subfunctions improve code organization by grouping related tasks while maintaining modularity. Function handles offer flexibility by treating functions as variables, allowing dynamic execution of operations.
Understanding these types of functions in MATLAB helps you select the most efficient approach for your programming tasks, improving both performance and maintainability.
The principles you learn about MATLAB functions are more than just writing code. They represent fundamental concepts of technical programming. As you create more MATLAB programs, these function techniques will help you develop efficient solutions for complex problems. Are you a CSE student who wants to start your data engineering career? Talk to upGrad’s panel of expert career counselors to get the best guidance and build a successful career.
Explore upGrad’s top certification courses and boot camps:
Expand your expertise with the best resources available. Browse the programs below to find your ideal fit in Best Machine Learning and AI Courses Online.
Discover in-demand Machine Learning skills to expand your expertise. Explore the programs below to find the perfect fit for your goals.
Discover popular AI and ML blogs and free courses to deepen your expertise. Explore the programs below to find your perfect fit.
References:
https://in.mathworks.com/
https://www.spiceworks.com/tech/devops/articles/what-is-matlab/
https://www.mathworks.com/help/matlab/functions.html
https://in.mathworks.com/help/matlab/matlab_prog/types-of-functions.html
http://www.ws.binghamton.edu/fowler/fowler%20personal%20page/ee521_files/matlab%20functions.pdf
https://in.mathworks.com/discovery/matlab-gui.html
https://www.matlabassignmentexperts.com/blog/event-driven-programming-in-matlab-guis.html
https://in.mathworks.com/help/matlab/matlab_prog/nested-functions.html
http://matlab.izmiran.ru/help/techdoc/matlab_prog/ch_fun14.html
https://matlabexamples.wordpress.com/2020/06/16/subfunctions-in-matlab/
https://iastate.pressbooks.pub/matlabguide/chapter/chapter-8-functions-and-function-handles/
https://www.mathworks.com/help/matlab/ref/plot.html
https://in.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html
https://bijen-adhikari.medium.com/anonymous-functions-in-matlab-part-3-9bbab83e0146
https://in.mathworks.com/help/matlab/error-handling.html
https://www.mathworks.com/help/matlab/index.html
https://www.mathworks.com/help/matlab/language-fundamentals.html
https://www.mathworks.com/videos/matlab-compiler-overview-92528.html
https://www.mathworks.com/help/matlab/matlab_prog/case-and-space-sensitivity.html
https://web.cecs.pdx.edu/gerry/MATLAB/programming/basics.html
https://in.mathworks.com/help/matlab/matlab_prog/scripts-and-functions.html
https://in.mathworks.com/help/matlab/matlab_prog/private-functions.html
https://in.mathworks.com/matlabcentral/answers/216376-how-do-i-define-the-recursive-function
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Top Resources