Today we will be covering the following topics:
1. User Defined Functions – A general function can go under many different names – an M-File Function, M-Function, or sometimes people just refer to it as a function
2. Nested Functions
3. Nargin and Varargin
4. Recursive Functions
VIDEO COMING SOON
User Defined Functions
Note before we begin: User Defined Functions are not the same as the built-in functions we discussed in previous lessons.
A function is like creating a script in MATLAB in the sense that it has its own space for typing code that isn’t the Command Window, but it’s more flexible in that there can be multiple inputs and outputs in one line. We specifically have to click the top left “Function” button, to create a function file rather than a script. This is shown below. Press the New button circled in red, then select Function:
Once you click the Function button, this screen comes up. The top part, circled in red, is the window where the function appears. This is the same window where previously, a script would appear.
The function has inputs and outputs, also called input and ouput arguments, or parameters. These are circled in red, and are labeled as output_args or input_args as default. Input arguments are values that the user will enter to run the function, and output arguments are the values that MATLAB outputs as an answer after running the code. You can put none, one, or multiple input and output arguments in here as well. The first line of code that contains the function name and input/output arguments is called the Function Definition Line.
The function is saved as a function file, and when we save this file it needs to be saved as the name of the input argument. When the file has to be saved, click the Save button on the top left, then in the drop down menu select Save As. The default name of this function (the name it must be saved as) is also highlighted in yellow. Note that names must only begin with a letter and be 63 letters or less. The file is saved with a .m extension.
When you select Save As, this pops up. Note that the file name is saving as untitled6, which is the same as the name of the function in the image above. If you want to save the function file as something else, you need to change the yellow highlighted name in the image above.
Once it’s saved, it will save to a MATLAB folder on your computer by default, unless you change it to a different location.
Here are some differences between scripts and functions before we move on:
Let’s take a look at writing code within this function file. Whenever we type code within a script or function, it is called creating a program.
For example, say we wanted the user to enter the base and height of a triangle, which will be two inputs (inputs in red). The output of the function will be the area of a triangle using that given base and height (output in light blue – also, when you have only one output, the square brackets aren’t necessary, but you can add them like I did like [area]). I also changed the name of the function to be called triangle_area, highlighted in yellow.
Now that we have defined these three things – changing the name of the function to what we’d like (usually it reflects what the code is going to be used for, in our case it was triangle_area), then changing the inputs and outputs to reflect how many of each there are (in our case, we have 2 inputs and 1 output), we can focus on writing the code, which will be typed where the green words are in the image above.
For our code, it needs to output the area of a triangle. The answer will be given in the variable area because that’s our output. This is why I have set the equation of a triangle (which is (base*height)/2) equal to the variable area. The one line of code I have written is area = (base*height)/2.
Now before we run it, we have to save the code as the name of the function, triangle_area.m. The .m should always be there.
Now that the file is saved, we need to execute/run it. To do this, we can’t hit the Run button like we do with scripts. We need to call the function in the Command Window. This means to just type the name of the function, replacing the variables with numbers, into the Command Window.
Say I use a base of 5 and a height of 10 (I will assume this is in meters, but your code should specify units otherwise). I have circled this in red in the Command Window:
When I hit the Enter key on the keyboard, MATLAB runs the code I had typed to find the area. It outputs the area variable, which is the answer to the area of the triangle with base of 5 and height of 10, which is the output of the function. This is circled in the Command Window below:
Let’s try another example, where we have two outputs and one input. There are a few things to note here:
(a) I have named the function circle_area_circumference, which is in the very first line of the program in the image below. You need to make sure your function is saved under this name exactly, or it won’t work
(b) The outputs I chose (highlighted in blue) are the area and circumference of the circle that MATLAB will output as the answers to the code we type
(c) The input (highlighted in purple) is the diameter
(d) The three lines of code (highlighted in yellow) between the first and last lines are what MATLAB will execute to obtain the outputs. Within these lines, I have typed the equation for circumference of a circle, equation for area of a circle, and defined what the radius is. This is because our input argument was only the diameter, so you have to write an equation that relates the radius to the diameter, so MATLAB can then use radius in the equation of the circle.
You could, alternatively, also just define the area of a circle in terms of diameter rather than using radius and having to define that first, but either way works.
Now to run a function, remember that we can’t just hit the Run button at the top of the page. We need to call the function in the Command Window, which means writing the name of the function in the Command Window, and entering the arguments in brackets next to it. This is what I would type in the Command Window if I chose a diameter of 5 (highlighted in red) – notice how I matched it to the name of the function. which I’m pointing an arrow to (they must match for it to work, I didn’t use that name in the Command Window just because):
When I hit the Enter key, this is what comes up as the output. I have highlighted them in yellow – the circumference and area, which are the two outputs in the first line of code as the output arguments.
Nested Functions
When you use one function within another function, it is called a nested function. Using one function within another is useful because if there are variables that are not within the main function but they are within the nested function, you can still access them.
Here are the main requirements to use nested functions:
(1) You cannot define a nested function inside conditional functions (eg. if-else, switchcase, while, for … these are discussed in future lessons)
(2) You must call a nested function directly by its name, or using the @ sign that you had created (with anonymous functions specifically)
(3) You need to define all variables explicitly. You cannot call a function or script within another function that will assign values to variables, unless those variables already exist in the Workspace.
Here is an example of what a nested function looks like. I have the main (parent) function called output, and then the nested function called secondfunction within it. I also have the name of the second function added within the parent function (notice Line 3 says secondfunction):
To call a nested function in the Command Window, call the parent function and not the nested one. All you have to do is type the name of the main function (including inputs if you function has any). I didn’t have any inputs, so the code executes and displays the messages in both the main function, as well as the message I had put within the nested function:
Nargin and Varargin
Nargin and Varargin are two commands that you can use with functions in MATLAB. Nargin is used to find the number of input arguments to a function, and Varargin is used to get a function to accept a variable number of input arguments. Usually, you will have a specified number of inputs to a function, but using the Varargin command can change that. They are usually used together in one function, because if you have a variable number of inputs, then you can check how many of the possible inputs have actually been input by the user.
Example – Using Nargin and Varargin
Here I will use both of these in one function. I want this function to take either one, two, or three inputs, but you won’t be able to specify this in the function inputs as we usually do. I will use varargin to specify as the function input, then I will check how many inputs the user has entered using nargin.
Here I have created a new function called test with an output of y. The input will be varargin, and then the only code within my function is nargin:
Now if I call this in the Command Window using the function name test, I will enter some random inputs, just to see if MATLAB will pick up on the number of variables because I used nargin within the function. I have entered the numbers 12 and 23:
Then the output of the function is 2. Since nargin will return the number of inputs that you have entered in the function, this is correct because we do have two numbers as the input. You can enter any number of inputs, and it will pick up on how many you have. We will cover more examples with this in a future lesson with Loops and Indexing.
Recursive Functions
A recursive function works like a loop – we will discuss loops, such as for loops and while loops, in a future lesson. Loops work by specifying a condition that has to be true in order for a certain block of code to execute, rather than executing all the code in your program (program meaning your script or function). This is similar to a recursive function. Recursion is the process of a function calling itself over and over again.
This is useful for certain problems, such as calculating a factorial. In mathematics, a factorial (denoted as n! so 1! is factorial of 1, 2! is factorial of 2, and so on) is the product of that number as well as all the numbers below it. For example, 3! means the factorial of 3, which is calculated by 3*2*1, which equals 6.
Let’s create a recursive function for calculating a factorial here:
Let’s go through the above code:
(a) I am creating a function by the name of factorial in the first line, so that I call the function back again in line 5. This is in the factorial equation, which multiplies the input number n by the previous number (n-1). The output is the variable x.
(b) We don’t want to stop by just multiplying the input number by the number before it though. The factorial should multiply all previous values by the input, including itself. This is why we need a loop, such as the if-else loop within the function – each time the recursive function is called, the value of n is decreased by 1, until it reaches 1. If we don’t include this loop, MATLAB will give an error – aside from that, we do need to be able to decrease the value by 1 each time the loop runs in order to multiply the input number by every number before it.
Putting these together allows you to get the factorial for a number. Here I find the factorial of 5 by calling the function from the Command Window:
This is the output: