12.6: Anonymous Functions

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    12.6: Anonymous Functions

    An anonymous function is a short function that is created directly in a script, in the Command Window, or inside another function file. Unlike regular functions, anonymous functions do not need their own separate .m file.

    Anonymous functions are useful when you need to define a simple mathematical expression and use it several times. They are especially helpful when working with plotting, numerical integration, root finding, and other numerical methods.

    The basic format is:

    functionName = @(inputVariable) expression;

    The symbol @ tells MATLAB that we are creating a function handle. A function handle is a variable that stores a reference to a function. The input variable is placed inside parentheses after the @ symbol.

    For example, to define

    \(f(x) = 3*x^2 + 2*x - 1\)

    we write:

    f = @(x) 3*x.^2 + 2*x - 1;
    

    After creating the anonymous function, we can evaluate it just like we would call any other function.

    For example:

    f(2)

    returns:

    12

    because:

    2^2 + 3(2) + 2 = 12

    We can also pass an array of values to the function:

    x = 0:5;
    y = f(x)
    

    This evaluates the function at every value in the vector x.

    Notice the element-by-element operator .^ in the function definition. This allows the function to work with both single numbers and arrays of x-values.

    Note

    When writing anonymous functions that may receive arrays, use element-by-element operations such as .*, ./, and .^ when appropriate.

    Anonymous Functions with More Than One Input

    Anonymous functions can also have more than one input. For example, suppose we want to define the area of a rectangle as a function of width and height.

    Example \(\PageIndex{1}\)

    Calculating the area of one or many rectangles.

    % define an anonymous function for area of a rectangle
    areaRect = @(width, height) width .* height;
    
    % calculating the area of one rectangle
    width = 3;
    height = 4;
    
    area = areaRect(width, height)
    
    
    % Calculating the area of 3 rectangles.
    widths = [2 3 4];
    
    heights = [5 6 7];
    
    areas = areaRect(widths, heights)
    Solution

    clipboard_e46d7ac431e3c5c3531751e65ec67a9d3.png


    This page titled 12.6: Anonymous Functions was last modified on Tue, 30 Jun 2026 02:11:51 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.