Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Software Engineering Tutorial
  • Software Development Life Cycle
  • Waterfall Model
  • Software Requirements
  • Software Measurement and Metrics
  • Software Design Process
  • System configuration management
  • Software Maintenance
  • Software Development Tutorial
  • Software Testing Tutorial
  • Product Management Tutorial
  • Project Management Tutorial
  • Agile Methodology
  • Selenium Basics
Open In App
Next Article:
Inline and Anonymous Functions in MATLAB
Next article icon

Anonymous Functions in MATLAB

Last Updated : 15 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

A block of code that is organized in such a way that is reusable for the entire program. Functions are used for reducing efforts made by writing code and making the program short, and easily understandable. 

There are different syntaxes for declaring a function in different programming languages. In this article, we will specifically revolve around the syntax of declaring a function in MATLAB.

Function Declaration in MATLAB:

Matlab possesses different types of functions. Some functions are defined in a few lines, whereas some take the entire program named over the function for its declaration. 

Syntax:

function [i1,i2,...,in] = func_dec(o1,o2,...,om)

Now we see the MATLAB program. In this program the name of the function is funx_dec and hence you have to save the file with the same name, i.e., func_dec.m. Here, the input parameters are i1, i2, i3,..., in, and the output parameters are o1, o2, o3, ..., om. Let's understand this syntax via practical implementation.  

For this, we create a function to find the maximum among three numbers.

Example 1: 

Matlab
% MATLAB program for function function [ans] = greatest_no(x,y,z)     if x > y         if x>z             ans = x;         else             ans = z;         end     else         if y>z             ans= y;          else              ans=z;         end     end end 

Output:

Anonymous Functions:

The anonymous function is one of the most powerful tools of MATLAB, as it could define a function without an M-file. Anonymous functions in MATLAB, unlike normal functions, are associated in a variable, not in files. When you declare a variable for an anonymous function then the data_type of that particular variable is function_handle. 

As it is an anonymous function whose value is to be stored in a variable, and thus there could only be one output, however, there could be many inputs for it. As the function is written in a single line and thus it contains only one executable statement. However, for executing more than one statement you can use a temporary function inside the anonymous function.

Syntax:

func_name = @(inp_argu)math_exp  // The @ operator is used to initialize anonymous   functions and handles function .

Let's understand the syntax of anonymous function using an example of finding cube function:

Example 2:

Matlab
% MATLAB code for anonymous function cub = @(x) x.^3; 

Output:

Here, the syntax is the initializing of the anonymous function is done with '@', followed by input parameter x, written in between the parentheses '( )', and then the statement to be executed is written. 

You can also use the variables, that were declared earlier in your anonymous function. The values persist even if you clear the variables, after the declaration of the anonymous function. Let's understand this by the following parabola equation.

Example 3:

Matlab
% MATLAB code for function % variable declaration a = 3 b = 1 c = 43 para = @(x) a*(x*x) + b*x +c % parabola equation clear a b c 

Output:

We can use the anonymous function both in the command line window, as well as could be saved to load later by calling it while running other programs or through the command line. If a function is going to be used a limited number of times, then anonymous functions are great to go with. It is also used to construct higher functions. 

Now's let's understand Matlab anonymous functions different usages.

Anonymous functions of no variable:

We can use the Matlab anonymous function without even passing a single variable. For such anonymous functions leave the parentheses () blank. 

Example 4:

Matlab
% MATLAB code for no variable anonymous function print = @() disp("This is an anonymous function."); print(); 

Output:

ans: This is an anonymous function.

Here, we have not used any variable in the input or even in the function. In this function, we have not even used any variable in the function, however, we could assign any value by evaluating it also.

Anonymous functions of one variable:

Using Matlab function without variable is not convenient at all. We don't need the same thing to happen again and again, we actually need to perform some calculations over time. For these, we need to put some variables under the parentheses. We had our previous cub example of variable, let's have another example of finding  x\sqrt{x}    using an anonymous function.

Example 5:

Matlab
% MATLAB code with variable expression = @(x) x*sqrt(x); expression(4) 

Output:

ans: 8

Anonymous function with more than one variable:

In certain cases, more than one variable needs to be passed and evaluated. For such cases, we can pass more than one variable in the Anonymous function to evaluate. Let's evaluate the expression {x^3+ y^2 - z} using an anonymous function.

Example 6:

Matlab
% MATLAB Code anonymous function with more than one variable expression = @(x,y,z) x.*3+y.*2-z; expression(12,5,19) 

Output:

ans = 27

Nested anonymous function:

Sometimes we need to perform more than one line of code evaluation, in such cases, we need to use the nested anonymous function. The nested anonymous function evaluates the inner function first and then the outer one gives the output. Let's understand such king of function with an example of solving a definite integral \int_{1}^{6} (12x^3 -9x^2+2) dx.

Example 7:

Matlab
% MATLAB Code for Nested anonymous function expression = @() integral(@(x) (12*x.^3 - 9*x.*2 + 2),1,6)  expression =    function_handle with value:      @()integral(@(x)(12*x.^3-9*x.*2+2),1,6) 

Output:

ans = 3580

Passing an anonymous function as a function handle to other functions:

For the constructions of higher functions, we can pass an anonymous function as the function handle to other functions. For example, create a function handle with input parameter as func(output of the anonymous function), and x.

Example 8:

Matlab
function y = functionHandle(fun,x)     fun = fun(123);     y = fun * x; end 

Output:

>> functionHandle(@(x) sqrt(x), 12)      ans = 133.0864

Next Article
Inline and Anonymous Functions in MATLAB
author
geeky01adarsh
Improve
Article Tags :
  • Software Engineering
  • Geeks-Premier-League-2022
  • MATLAB-Functions

Similar Reads

  • Inline and Anonymous Functions in MATLAB
    Methods are also popularly known as functions. The main aim of the methods is to reuse the code. A method is a block of code that is invoked and executed when it is called by the user.  Inline FunctionInline functions are the kind of functions which is defined in one line. that's why this type of fu
    4 min read
  • Find() function in MATLAB
    The find() function in MATLAB is used to find the indices and values of non-zero elements or the elements which satisfy a given condition. The relational expression can be used in conjunction with find to find the indices of elements that meet the given condition. It returns a vector that contains t
    3 min read
  • Scripts and Functions in MATLAB
    In MATLAB there are a different kinds of files dedicated to MATLAB codes. They are the following: ScriptLive ScriptFunction only fileClass fileNow only the live script is the only one of these which has a different extension name; all other three use the standard .m extension. In this article, we sh
    2 min read
  • Map Function in MATLAB
    A map function basically takes the elements of the array and applies a function to each element.  The resultant output is of the same shape as the array, but the values are the result of the function. In MATLAB, there is a similar function called arrayfun(), which we can be used to achieve the same
    2 min read
  • Local Functions in MATLAB
    Functions in any programming language are some blocks of code, which could be reused whenever required, by just calling the name. It reduces so much of human effort and also rewriting of the same code, and makes the entire code big. Declaring a function:Before moving forward let's see how actually t
    2 min read
  • Filter Function in MATLAB
    The filter function or 1-D digital filter is a function in MATLAB that is used to filter a given noisy data by removing the noise in the data and sharpening or smoothing the input function. As MATLAB provides a dedicated Signal Processing Toolset, the filter function comes handy to remove noise from
    3 min read
  • Inline Functions in MATLAB
    Inline functions are those functions that are defined in one line, also called one-liner for the same reason. In MATLAB there are two types of inline functions, inbuilt and user-defined. Let's take a look at both of them. InBuilt inline Functions:MATLAB has many mathematical functions built-in which
    2 min read
  • Defining Function Handles in MATLAB
    A MATLAB data type that represents a function is called a function handle, in other words, we say that The function handle is a typical data type in MATLAB. Function handles can therefore be modified and used in the same way as other MATLAB data types. Using function handles in arrays, structures, a
    3 min read
  • Nested Functions in MATLAB
    Functions in any programming language are some blocks of code, which could be reused whenever required, by just calling the name. It reduces so much of human effort and also rewriting of the same code, and makes the entire code big.  Declaring a Function: To declare a function in MATLAB we use given
    3 min read
  • Void Function in MATLAB
    When defining void* output in the library definition file, MATLAB specifies that the argument MLTYPE must be one of these: a typedef from the library. Use only to produce scalar data. If the library has a typedef defined for void* that uses that name, MATLAB specifies MLTYPE as the new type name in
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences