Skip to main content
Engineering LibreTexts

Chapter 15: User Defined Functions

  • Page ID
    89920
  • \( \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}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)

     

    Fig15.1
    Figure 15.1: Luckily for us, MATLAB functions aren’t THIS complicated.

     

    Functions are a fundamental part of mathematics and most students are familiar with how they work. In math class, you were likely taught that you can think of functions like little machines (figure 15.2) that associate a unique number \(y\), with any given number, \(x\). You may have even learned the terminology that the \(x\) value is the input, and the \(y\) value is the output.

     

    Fig15.2
    Figure 15.2: The function of a little number manipulation machine

     

    If you can understand how a mathematical function works, you are actually well on your way to understanding how MATLAB functions work! MATLAB functions work in the same way as mathematical functions. You have one (or more inputs), manipulate the input(s) according to some rules, and then you return one (or more outputs).

     

    Learning Goals

    In this chapter, we will learn the how to create our own MATLAB functions and why we should. That means learning:

    • What MATLAB functions are and why they are important.
    • Reviewing some of the most common MATLAB functions we have already been using.
    • Where the help text of a function lives and why it is important to write good help text.

     

    MATLAB Built-In Functions

    As mentioned above, a MATLAB function is very similar to a mathematical function. You have already been using MATLAB functions throughout this book! I have been careful to distinguish functions from other bits of code by appending a set of parenthesis on the end whenever we are discussing functions (i.e. sin()). Let’s investigate a few MATLAB built-in functions to understand how functions work:

    • sin()
    • mean()
    • max()

     

    Try It!

    It is worth taking a moment and reading the help text for the 3 functions listed above. To do so, open MATLAB and type in >> help function_name into the command window. You should replace function_name with the function of interest (e.g. >> help max). You do not need to memorize anything but go ahead and read through the help texts to get an idea of how they work.

     

    % Remember, Octave has help text too!
    
    help 

     

    sin() Function

    The sin() function is perhaps the easiest to understand because you are likely already familiar with trigonometric functions. The sin() function takes an input, angle in radians, and returns an output, the ratio of the length of the side of a right triangle that is opposite that angle to the length of the longest side of the triangle.

    An example of how to use the sin() function would look like this (make sure you are trying it for yourself in MATLAB!):

     

    x = 2.1; % in radians
    
    ratio = sin(x)

     

    Notice how the output of the sin() function is assigned to the ratio variable.

    Now the real question is, how does MATLAB calculate that ratio? Well, MATLAB engineers have created thousands of numerical algorithms stored in functions that they supply with the product. This brings us to the central idea behind functions: functions exist to make it easy to run snippets of code with different inputs.

    Key Concept: Functions exist to make it easy to run snippets of code with different inputs.

    An example would be the sine trigonometric function. Most engineers and scientists do not want to have to program the algorithm that calculates the sine of an angle every time they need to calculate sine. That is too much work! So you can create a function that calculates the sine of an angle, name it something that makes sense (in this case sin()), and allow it to work for any input!

     

    mean() Function

    Recall that the mean() function accepts an array as in input, and returns the average value of the values inside the array as the output.

    An example of how to use the mean() function could look like this:

     

    array = [9 3 1 3 5];
    
    avg = mean(array)

     

    When you try this example, you should notice that the value stored in the variable average is 4.8, the mean of the array! Keep in mind that you could have used a few different functions to calculate the exact same value. Recall: ({average}={sum}/{count}). Therefore:

     

    array = [9 3 1 3 5];
    
    % avg = mean(array)
    
    avg_long_way = sum(array)/length(array)

     

    Again give it a shot. You will notice that the value in avg is the same as avg_long_way which is unsurprising. However, you can imagine that if you had to constantly type out the long way, it would get tedious. The other thing to consider is that sum() and length() are functions themselves! Take those away and this problem of calculating a mean gets really complicated.

     

    Key Concept: Functions make your code easier to read and easier to type.

    The key concept here is that functions make your code easier to read and easier to type. So when you have an algorithm that is likely to get run over and over again, it is a good idea to make a function for it!

     

    Question 15.1: Relational Operator Review

     

    max() Function

    Next up, lets consider the built-in function max(). This particular function is interesting because of its flexibility. The function accepts an array as an input and returns the maximum value in that array as its output. That in itself is cool, but not that exciting (hopefully you read the help text for max() and know where this is going). The exciting part is that max() can optionally return the index where the maximum value is located within the array!

    To see this in action, let’s try an example. We can use the array variable still located in our workspace from the previous example:

     

    array = [9 3 1 3 5];
    
    biggest = max(array)

     

     

    That will store the number 9 inside the biggest variable. Cool, but not exciting. Take an account of your workspace variables. Now try:

     

    array = [9 3 1 3 5];
    
    [maximum, index] = max(array)

     

    Look at your workspace now. Notice that it created two new variables, one called maximum that has the number 9 stored in. The execution of that code also created a new variable, index with the number 1 stored in it. The 9 is the biggest number in the array, and the 1 is the index of where the number is located.

    The first key concept to learn from this example is that MATLAB functions can accept multiple inputs and can return any number of outputs.

    Key Concept: Functions can accept multiple inputs and can return any number of outputs.

    To be specific, when you are creating a function:

    • You can require any number of inputs. For example, you can require your user to specify at least one array, or you can say that a minimum of two arrays is required, etc.
    • You can make any number of inputs optional. For example, you can have one required, and one optional input.
    • The only output that is not optional is the first output. All other outputs from a function are optional. That means that you can not force your user to accept two outputs from your function. This is an important thing to consider when designing your own functions.

    Let’s continue with the max() function to investigate our next key concept. If you have been doing your brain workouts, you read through the max() help text. See figure 15.3 below, specifically the highlighted region.

     

    Fig15.3
    Figure 15.3: A portion of the MATLAB help text for max().

     

    Notice how well this function is described! It shows an example of how to use the function ([M,I] = max(X)) and gives a nice description of how it works.

    The second key concept is that well-written help text is critical to writing a good function. If the documentation for this function was poorly written or confusing, no one would use it!

    Key Concept: Well-written help text is critical to writing a good function.

    A good function is one that is well documented, not only for your users but for yourself! Variable names and algorithms always make sense when you are working on them, but when you put them down for a while, you need good documentation to ensure that your code is still usable.

     

    Question 15.2: The Key Concepts

     

    User Defined Functions

    Now that we have seen how MATLAB built-in functions work and what they are used for, it is time to create our own functions. However, before we can begin making our own functions, we need to have a quick review of the current working directory.

     

    The Importance of the Current Working Directory

    Up until this point, you could have gotten away with bad file management. You could store all of your files in the same folder, and put them all on your Desktop, it hasn’t mattered. However, if you want to use your function files, you are going to have to be cognizant of your current working directory and your path.

    As an analogy, think of MATLAB as a mechanics garage and think of functions as different tools. MATLAB comes pre-loaded with a bunch of tools (sin(), length(), max(), etc) and already knows where they are located. When you make a new tool called impact_driver(), you can store it anywhere. Maybe you are storing your new impact_driver() in the shed out back (your My Documents folder). Maybe you threw it into the lake. MATLAB has no idea where to look for it. So when you tell MATLAB you want to use your new impact_driver() it does the logical thing, it looks where you are standing (your current working directory). So if you tell MATLAB, “I want to use my new impact_driver()”, and you are standing in your shed, MATLAB will check the shed for the tool. If it can’t find it in the shed, MATLAB will check the garage (this is called the path). If it can’t find it where you currently are (your current working directory) or the garage (the path) then it gives up. I don’t blame it! It isn’t a magician.

    The moral of the story is that MATLAB will always look in the current working directory for your user-defined functions.