11.5: Anonymous (or In-Line) Functions

Matlab and Octave Programming for STEM Applications · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

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

    11.5: Anonymous (or In-Line) Functions

    There is an option in MATLAB to create an in-line function, without creating a regular function file or subfunction. It only works if the function is simple enpough to be written on a single line of code. The syntax of this option is confusing to most students. This option is never necessary, but can be convenient if the function is a particular function for only 1 script. Such in-line functions are called often "anonymous" functions. This name "anonymous" functions is common, but misleading, since such a function does have a name. (Anonymous functions are an advanced topic and is optional for this textbook.) A general purpose user function should be put in its own file.

    Using the example of the previous section, the function can be defined as an in-line function with this syntax:

    y_fun1 = @(x) log(x)./x.^2 -0.1;
     

    The left side states the name of the function.

    The @(x) states that the function is a function of x.

    The rest of the right side is the formula that will be computed.

    For an in-line (anonymous) function the function name is the function handle, so when we use it in fzero, we use the name without the @ as shown here:

    x_solution = fzero(y_fun1, 4)

    .


    This page titled 11.5: Anonymous (or In-Line) Functions was last modified on Mon, 26 Jun 2023 04:43:43 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Carey Smith.