Lesson finished
Unlock all 27 lessons of MATLAB BasicsFull course ₹40,000 · paid
MATLAB Cell Arrays, Conditionals, Loops and User Input
A free lesson from Skill-Lync's MATLAB Basics course, on Grow by Skill-Lync · Last updated 16 Nov 2026 · Session: “Week 1 Session 2-Introduction to Matlab fundamentals and programming: Part_2”
What will you learn in this free MATLAB Basics lesson?
The lesson continues cell arrays and the ellipsis continuation, then covers if-else with the mod function, a for loop summing the first 100 numbers, and a while loop collecting prime numbers with isprime. It ends with the input function and an input dialog, and leads into file writing.
- Cell arrays and the ellipsis continuation
- If-else logic using the mod function
- For and while loops with break
- Interactive input with input and inputdlg
What comes after lesson 3?
Later in Skill-Lync's MATLAB Basics course (paid): lesson 4, Demonstration of For Loop; lesson 5, Demonstration of While Loop; lesson 6, File handling. The full course has 27 lessons (7 h 2 min of video); see the course overview or its price and syllabus.
Lesson transcript
Machine transcript of the lesson audio (lightly cleaned). Technical terms may contain errors; the video is the reference.
So in this section, we'll continue with cell arrays. We ended the previous section with cell arrays. We talked a little bit about cell array data type, where we said a matrix can have dissimilar entries. Cell array can facilitate that. An example is shown on the right, where we have matrix M defined with entries like mathematics, physics, chemistry, city names, and then numerical values. So when you enter M and hit enter, you'll get the cell array displayed, individual elements shown in braces. So like I said before, the braces indicate that the contents are cell array elements.
So one other construct in MATLAB is you would like to continue the line, more entries. For example, when you are building a matrix, sometimes the matrix entries could be much, much longer than 80 characters. What we know, in a typical programming language, a coding sheet had 80 characters, 80 columns to script the program. Also for readability, anything over 80 characters would be difficult to read in a page format. When you print the file out, or when you take a screenshot and you want to read, it's difficult.
So MATLAB has a construct called ellipsis. So if you would like to continue the line, in this case, after the semicolon, it doesn't have to be semicolon. We could abruptly end, for example, the first line with chemistry, with single codes, and then add ellipses to indicate that the line is continuing. So it doesn't, MATLAB does not process the ellipsis. It just understands that the line is still continuing. So ellipsis is the continuation character, so to speak. So that ends the data type section. We are moving on to loops and conditional statements.
Like any programming language, loops and conditional statements are necessary to implement repetitive calculation and, you know, logical statements. So we'll see how the format looks in MATLAB. So MATLAB offers if-else structure. It's called conditional if-statement. It has for loops. It repeats a specific number of times. While loop, and then there is a break statement, and there is an end statement. So we'll go into some more detail, hopefully in the next slide. Here are some examples how these loops and conditional statements can be used in MATLAB.
So the first one is an if-else construct, where the variable x is set to 5, and then to 7, and then to 2.5. And then a logic is built to check if the number is even or odd or neither. So at the very top, we have set it to set the value of x to 5. And then in MATLAB, there is a function called mod, modulo function. So the modulo function, what it does is, I mean, it takes two arguments. The first argument, the second argument is divided into the first argument.
And if there is a remainder, the mod function returns the remainder. So we check, you know, for even numbers, if you are dividing the value of x by 2, the remainder is going to be 0. For odd numbers, the remainder is going to be 1. And if it's neither, then you know it's not even or odd. So basically, we use that understanding to learn how the logical statements are implemented in MATLAB. The first one checks for the output from the modulo function. x is set to 5, and you expect the value to be 1.
So in this case, when the logic is executed, the if-else-if-else-end logic is executed, it returned, you know, the inference was odd, and then it returned the value of x. So it said input x is an odd number with value 5. Then x is set to 7. Then the inference was that input x was an odd number with value 7. When x is set to 2.5, the inference was that x was neither even nor odd. And we didn't really display the value of x in the third case.
So here is an explanation for mod. Mod calculates the remainder after the first argument is divided by the second argument. That's what we said in the previous slide. Also, there are a couple of other functions that we used. In the example, one of them is num2string. num2str, num2string. So the num2string function takes the input argument, you know, which expects a numerical value, and converts it into a string. That's what num2str function will do. The second function that you are introduced to is the disb. That's basically a display function.
You know, anything that's set within single quotes, within parentheses, will be displayed. That's what we found in the previous example, and that's what is being shown on the right. Now, let's move on to the loop implementation in MATLAB. The for loop is shown. Examples are shown on the right. So here the intent is to determine the sum of first 100 numbers, you know, starting with the 1. So we have set n to 100, and we also have set sum to 0, as shown on the right.
Now, the for loop has a syntax. You know, it's for, you have to specify a variable for the index, i, counter, so to speak. So i going from 1 to n, comma, the comma is not necessary in current MATLAB. It's kind of understood. So there we try to increment sum by adding the index value or the counter here in this case. So you loop through, i loops through from 1 to n, and you are keeping track of the sum at any given point. Then you are adding those numbers when i loops through from 1 to n.
And that's how you get the sum of the first 100 numbers. And when we enter sum, it returns 5050. And then, then I think the next example is showing how you can break out of the loop. So there we are trying to execute the loop. But within the loop, after sum equals sum plus i, we have added an if block. If i is greater than or equal to 50, so then execute break. So it will come out of the for loop. I mean, that's the whole intent of invoking a break statement, invoking a break command.
So in this case, so again, the loop has started at 1. It ran through the loop till i was 50. And when i was greater than or equal to 50, it came out of the loop, the for loop. So essentially, the sum that is being shown is the sum from 1 to 50. And we also know sum of n from the formula shown on the left, sigma i, i equals 1 to n, is simply n times n plus 1 over 2. So we can verify that.
So for n equals 100, the sum will be 5050. If we had used the formula above, n times n plus 1 over 2, for n equals 50. And if we use the formula, the sum of first 50 numbers would be 1275. So we allowed the top for loop to go from i equals 1 to 100. The bottom for loop we have terminated once i has gone past 50. We have verified the results in MATLAB. Also, we verified using our conventional understanding for sum of n numbers.
So that's about for loop. So there is another construct called while loop in MATLAB. An example is shown on the right. So here the intent is to find the prime numbers between 1 and 50. So let us see how we accomplish that. We initially set counter to 50. So we set prime numbers to an empty matrix. So we want to accumulate. You know how vectors, row vectors and column vectors can be defined in MATLAB. So here, prime numbers we want to initialize with an empty vector.
The two brackets shown basically create an empty matrix for us. And now the while loop construct is basically while followed by the condition, comma, and commands we want to execute within the while loop. And the while loop, the last statement in a while loop is an end statement. That's what we are seeing. Within the while loop, we have added a logical if. So the logical if is checking for a number being prime. Is prime is a MATLAB function that checks if the argument is a prime number.
In this case, we started with 50. You know, that's the number of prime numbers. We want to find out the maximum set of numbers that we wanted to use to determine how many of them are prime numbers. So we chose the first 50 numbers. So that's set to, we called it, we have assigned that value to a variable called counter. So it's now, you know, first pass in the while loop, the counter is 50. So it's checking if the counter is the value 50, is a prime number or not.
So is prime returns a Boolean value, 0 or 1. If the command is prime, result of is prime, is true, then it, you know, it returns a value of 1. If it's false, it returns a value of 0. So we are only trying to add the value to the empty matrix if it's a prime number. So we use the is prime to determine that. So you will see prime number vector kind of building up. So we have taken the previous vector and any time we find a prime number, we just add it to the vector.
And then we are decrementing the counter. So when we decrement the counter, the counter goes from 50 to 49, 49 to 48, so on and so forth. And the condition that we chose to use for the while is counter greater than 0. So as long as the counter is greater than 0, so that includes 1. So the counter goes, starts at 50 and goes all the way down to 1, which point it will exit the while loop. And whatever prime numbers the is prime logic has determined to be are accumulated within the while loop.
So once the prime numbers vector is built, we use another MATLAB function called sort. The sort, I mean right now the prime numbers vector had numbers in the descending order. Because we started, set the counter to 50, we started going down. So the prime numbers were really determined in that order, in the descending order. So the sort will change them into ascending order. The sort function, the prime numbers has been replaced with the prime numbers in the ascending order. And when we print them, it will show all prime numbers in that vector.
For example, the 2, 3, 5, 7, 11, etc, etc. So here what we are saying is that each prime and sort functions are MATLAB functions that help in the sorting process and determining the prime numbers for this exercise. So these are the steps we really followed, which has already been explained. So that completes the loops and conditions segment. Now we are moving on to inputs and outputs. So MATLAB has utilities to read input data interactively with prompts or dialog boxes and from the files. So here we will try to show a few methods.
So on the right in the command window, so we are using a function called input. So the input function itself takes a string, an input string. It takes two arguments. The first argument could be the prompt message. And the second argument will go over the second argument in the next example. So if the input is not a numerical value, for example, a string or a character, then you have to have a second argument. So let's go over the first example. So here we are using the input function of MATLAB by passing enter your age as the first argument.
So when the command is executed, so it will display enter your age, prompting the user to enter the age. And when user enters the age, it will return the age under answer because we have chosen to call it assign the returned value to variable called answer. So in the second example, we want to pass a second argument. So here, the goal is to not just use a numerical value as input, but an entire string of characters. I mean, here, the example shows how an entire address can be stored in answer.
And that's basically what is being shown. So when it prompts, enter your address, user will enter the 73 Atherton Circle, SW, Huntsville, Alabama, 35824, and the country. And the answer will return the exact string that has been entered. Here is a bit of an explanation. The input takes two arguments, the message for the prompt, and a flag as to return as a string. Returns whatever has been provided as an input. When the input function is used with one argument, it will evaluate the input and returns the result.
That's what we said. With two arguments, it will return input as a string without evaluation. And we have seen both examples. Now, there is another way to get data from the user. I mean, it's called input DLG, input dialog. Input dialog is another way to get user inputs interactively via a dialog window shown on the right. So for the dialog window, one needs to provide or set multiple variables. You know, the dialog needs a title. We have to identify the number of fields and the labels for each field and so forth.
So in this example, so we have, we called, we picked a variable called prompt and we have assigned the name, address, and phone number as three entries as a cell array. And remember, we are using braces here. So prompt will be a cell array. Then that's the prompt. So when the dialog command, input dialog, input DLG is executed, it's going to use prompt, the first input, as the field labels. And there's a dialog title, DLG title. We chose to call it user record in single quotes.
And we can also specify the edit field dimensions. So we chose to, you know, 25 as the length. It's a one by 25. It's a, it's a vector. 25 size for the first entry name, 40 character size for address, and 20 characters for phone number. We have provided those dimensions. Then def input, that's an empty matrix. I mean, there are, obviously there are more inputs we can provide, but for this example, you know, it's chosen not to, being very elaborate. So OPTS is set to on, and then the input DLG is called with, with those inputs, prompt DLG title, DIMS, def input, and opts.
And then it returned the dialog. So when the command was executed, it returned, the dialog window shown on the right, and the user will make the entries. Under name, one would enter his or her name. Similarly, under address, one would enter the address. And under phone number, one would enter the phone number. And when, when we click on OK, the cell array gets generated, and it gets populated as shown. So you will, you will see the data stored in variable answer, three by one cell array.
The first row has the name information. The second row has the address information, and the third row has the phone number. So we're trying to throw more light on options. So when options are set to on, so that will allow resizing the dialog window. So if it's off, then one would not be able to resize the dialog window. With, with OPTS set to on, one would be able to expand or shrink the dialog box. So the entries provided by the user interactively are saved to answer.
Once the user clicks on the OK, that's what we said before, the dialog box will disappear at that point. So both are shown on the right. So, so far we have seen how user can interactively provide data through the function called input and through a dialog. Now we will see how MATLAB can read data from a file. So we'll use the same prime numbers example. For that, so an Excel spreadsheet has been chosen. So the one on the top right, what we have is a, is a screenshot.
Excel spreadsheet with prime numbers. So basically here we are trying to save the output from MATLAB function or MATLAB session to a spreadsheet, Excel spreadsheet. So the continue how we can write to a file in MATLAB in the next section.