Using Loops and Indexing

In this lesson, we will be covering the following topics:

1. Loops with Indexing

2. Loops within Functions

3. Varargin and Nargin

4. Functions within Loops

video coming soon!

Loops with Indexing

We discussed both indexing and loops in previous lessons, but what if we have loops where we need to use indexing within them? Let’s say we want to find the factorial of any number that a user has input. The factorial is a mathematical function and is denoted by an exclamation mark. For example, 3! means factorial of 3, and it multiplies 3 times every value below it. So the factorial of 3 would be 3 * 2 * 1 = 6.

Now we will create a function that takes in a variable n:

We will first need to initialize the factorial output (the product of all the numbers, let’s call it p). The very first value it will start at is 1. If you start at 0, then every number you multiply it by will be 0!

Now if the user enters a number n, we need to be able to take that value and multiply it by all the previous numbers, and it will need to loop for each value it multiplies. This means we need a loop running from the initial value 1 through to the number entered, n. This means the for loop condition is from 1:n. I’ll set this equal to a variable f for factorial.

Now within the for loop, we need to put code that will execute when the conditions of the loop are met. We want to put an equation here that takes the value of the current product and multiplies it by the next number, until it has multiplied all the products together to reach the number that the user has input. This is what it will be (I added code to line 4, within the for loop):

Now let’s run it with an input of n = 3 and see what the output is: Notice how the value of p goes from 1 to 2 to 6. This means that MATLAB is taking the initial value 1 and multiplying it by 1 to get 1*1 = 1. Then taking that output of 1 and multiplying it by the next number 2, to get 1*2 = 2. Then taking 2 and multiplying it by the next number (and the last one we need to reach our input of 3), to get 2*3 = 6. The final value for the factorial of 3 (3!) is 6.

But what if we just wanted to output the 6, without all the previous values as it runs through the loop each time? For that, we can use an fprintf statement, that will just print the final value. fprintf was covered in a previous lesson, so I won’t explain the details here – but it can be used for printing sentences with variables. We will want to keep this fprintf statement outside of the for loop, because we only want the final value to show after the loop is completed. So I have added line 6, which uses the variable p that we want to display in a sentence. We will also want to include a semicolon to the end of line 4, so the values of the loop each time it goes through are not shown:

Now the output for n = 3 is the following:

If you check out the fprintf post (linked here) you can change the statement to display a specified number of decimal places, so it won’t be 6.000000. Other than that, this is the final answer!

Loops within Functions

Now lets do an example with loops being used within functions – say we want to calculate the sum of the first n terms in the series 5*a + 6. Let’s type this into MATLAB first:

We can create a function so the user can enter which term of the function they want – so n = 1, n = 2, etc. If n = 1, then you substitute in a = 1, and so on. Let’s make a function that has an input of n:

Now for any value from 1 through to the value n that the user enters, we want to calculate the sum. You need each new value to add onto the previous value, so you’ll need a loop (a for loop works well for this) within this function. Before we add the loop, we need to initialize the output of the function – let’s change the output to sum. Then this variable sum needs to equal 0 in the beginning, so that the sum of all the numbers will start with 0:

Then we add the for loop – for values of the variable a going from 1 to n. I will indent this loop because it’s within a function, and it’s good practice to do this when you have functions or loops within one another.

Now within the for loop itself, we need to put a statement to execute if the conditions are true. We wanted to substitute that value of a (the same value we choose for n) into the function, find the value, and do that for all the previous values of n to sum them up.

For example, if I input n = 3, then we want MATLAB to substitute that value of n in for a in the equation 5*a + 6. Then we will do the same thing for the value of n = 2, then n = 1, and then we will add them all together – that’s what the “sum” of all these values means. It’s the value of that equation at the number we put in, plus all the numbers below it. This will be done by setting our equation 5*a + 6 equal to the output of the function, sum (line 4). Then we will need to add sum to this again, because it will add together all the previous values of the sum when we do this:

Varargin and Nargin

Usually, functions use a fixed number of inputs, such as this function below that has two inputs x and y:

function plot(x,y,varargin)

Varargin is used when you want to know how many inputs a function is using, so you will specify this using varargin.There is a way to enter a variable number of inputs – this works by using nargin to let MATLAB know that you are not going to have a specific number of inputs, but rather it can change. There is a way to enter a variable number of inputs – this works by using nargin to let MATLAB know that you are not going to have a specific number of inputs, but rather it can change.

Nargin is a second command that can be used, and usually it is used when you have varargin earlier in the code. Using nargin will output how many variables you are actually using. Let’s do an example of how both nargin and varargin can be used.

Suppose we want to write a function where a user can enter some inputs. They can either enter two numbers – if they do that, then the numbers are added. Or they can enter three numbers – if they do that instead, then the numbers are multiplied. See here how there are different things we want the function to do depending on the number of inputs. How will we make a code for this?

First, we will create a function:

Then we will add in the user inputs – a, and b. There are always going to be two inputs, but the third one is optional. This is why we only define two outputs in the function.

Now, we will add varargin as an output along with a and b. This tells MATLAB that we may have two inputs, and then possibly some more:

Now that we have set up the function to accept multiple inputs, we need to define what we want the function to do once it has those inputs. In the question, it says that the numbers should be added if there are only two inputs. So we will put a+b in the function body:

Then we will need to check whether the user has entered more than two inputs (the only option we want is to have three inputs if it’s not two). For this, we will use an if-else statement with nargin. This if-else condition will check whether nargin is equal to 2 or 3, since we only want the user to enter either 2 or 3 inputs. If it’s more than this, we will give an error message. So we check whether nargin is equal to 3 – we need double equals signs because it is checking whether nargin is equal to 3 inputs.

Note: A single equals sign is used when you are actually assigning a value to a variable, so if we were telling MATLAB that we wanted some variable to be equal to a specific number, which are are not since we are doing a comparison to see whether it is equal to 3 or not.

Now we want to multiply the numbers (as the question stated) if we have three inputs. But we never entered three input variables into the equation! We entered a, b, and varargin. So these are the variables we must use when multiplying all three together. So the first two variables will be multiplied (a*b) and then the third “variable” varargin will be called using curly brackets – we will use varargin{1} as the third variable. We will also set it equal to the variable multiply – but it will have to be written as multiply{1}. The number in the curly brackets indicates that you are adding on that many more variables to what is already indicated. Since we had indicated a and b as inputs, {1} means we are having three inputs total, {2} would mean four inputs total, and so on.

Now in the output, let’s try entering two numbers and see what happens. Notice how the numbers got added up, just as we expected:

Now let’s try entering three numbers. Notice how the numbers are multiplied, just as we expected!:

Functions Within Loops

We discussed both functions and loops in previous lessons, but what if we wanted to call a function within a loop? Well, there’s a way to do that! Say we have a for loop in one MATLAB script, and the condition is that if the variable a (from our function) is equal to 1, the loop will execute:

I want to “call” the function that I made doing the varargin/nargin example, (or I can call this function in general without the loop too). Now the name of the function we had created earlier was untitled3, and it could accept either 2 or 3 inputs. To call this function, you need to type the function name right into the loop, along with the inputs you want to use. Let’s use b = 5, and you can leave a as it is because you already defined that it should equal 1 right within the conditions of the for loop:

Now that we have two inputs, it should add them together to get 6, which is what it does in the Command Window. You can just hit the Run button at the top to run this, rather than having to type the name of the function in the Command Window to run it (check out the previous lesson on functions if you don’t know how to run them):

If you entered 3 inputs, it would be the same – just put a third number right in the brackets, and it should multiply them together as we defined for three inputs in the function above.