Skip to main content
Engineering LibreTexts

5.1: User-Defined Functions

  • Page ID
    14936
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    Up to now, the M-files that you have created are called “script” files. Now we use the editor to create function M-files. Why would you want to do this? Well, Matlab has many built-in functions, but you may need to create your own to solve a specialized problem.

    Lets look at how a function is put together. In the command window, if you were to type

    >> help sin

    you would get

    SIN Sine of argument in radians.
    SIN(X) is the sine of the elements of X.

    See also asin, sind

    Reference page in Help browser
    doc sin

    In reading this, you can see the purpose of the function, the correct usage of the function and references to additional related functions. When you create your own functions, you will also need to create similar information.

    Here’s how to create a function in Matlab. In the Editor window, follow these steps:

    1) On the first line(s) put comments that describe the function and, most importantly, a usage statement or HOW THE USER ENTERS THE FUNCTION!!!

    2) On the next line, put the word function followed by:

    1. In [ ], put the variable(s) (separated by commas) for the function output(s).
    2. The = symbol
    3. Your function name
    4. In ( ), put the variable(s) (separated by commas) for the function input(s).

    3) On the following lines, put the calculations that define the output variables based on the input variables.

    Easy right??

    A couple of comments before we get to some examples.

    Key Idea 1

    Function Tips:

    1. If you have exactly one output the aren't needed (see step 2a)
    2. Functions must follow the same naming conventions as for variables (do a Google search)

    Let’s look at an example of a function that computes the area of a triangle.

    Example 5.1.1: Area of a triangle function

    Here is the syntax that you would type into an editor window:

    % Usage: Area=TriangleArea(base,height)
    % Inputs: base and height are scalars
    % Output: Area - area of a triangle

    function Area=TriangleArea(base,height)
    Area = 0.5*base.*height;

    Now save this file as TriangleArea.m. Your file name must exactly match the name of the function (except for the .m part) or else the function will not run.

    In order to execute any function, you cannot use the Matlab run button. You must run the function from the command window or another M-file since you need to provide the input(s). First, check that you have provided enough comments about how to use the function:

    >> help TriangleArea

    which will give your description of how to use the function. Now, run the
    function with:

    >> A = TriangleArea(3,4)

    A =
    6

    Note

    In the program TriangleArea.m the variables Area, base and height are called local variables. That means they are only used in this specific program. They don’t appear outside the function (or in the Workspace).

    Example 5.1.2: Rectangle function

    Here is the syntax that you would type into an editor window:

    % Usage: [Area,Perimeter]=Rectangle(base,height)
    % Inputs: base and height are vectors of the same length
    % Outputs:
    % Area - area of a rectangle
    % Perimeter perimeter of a rectangle

    function [Area,Perimeter]=Rectangle(base,height)
    Area = base.*height;
    Perimeter = 2*(base+height);

    Now save this file as Rectangle.m Again, make sure the usage comments are correct:

    >> help Rectangle

    to see your helpful comments. Now run the function:

    >> [A,P] = Rectangle(3,4)

    A =
    12
    P =
    14

    Here again we are reminded of the fact that Area and Perimeter are local to the function, so when we run the function, we can call the outputs by different names. When we run the function we use the shorter A and P to store the areas and perimeters.

    What happens if you try to run the function without output variables? Try

    >> Rectangle(3,4)

    ans =
    12

    You only get the value that would have been assigned to the first output variable (here it’s the area). Since the calculations are just as they would be for matrices, we can try:

    >> base = 1:4; height = [3 6 10 12];

    and run the function:

    >> [A,P] = Rectangle(base,height)

    A =
    3 12 30 48
    P =
    8 16 26 32

    which gives us the areas and perimeters of the rectangles of the corresponding bases and heights.

    Here are a few commands of interest:

    nargin('TriangleArea') (number of inputs)
    nargout('TriangleArea') (number of outputs)
    nargin('mesh') (variable number of inputs)
    type('TriangleArea') (returns code of M file)

    One more example:

    type('sin')

    gives an output of ‘sin is a built-in function, which indicates that this last one is a built-in function whose code is not accessible.


    This page titled 5.1: User-Defined Functions is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Troy Siemers (APEX Calculus) via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.