MATLAB can implement common control flow operations such as if statements. Learn how to build an if statement.
- [Instructor] Now let's take a look at how MATLAB handles if statements. Once again, I'm going to clear the workspace and the screen. And then let's go ahead and open up my first script again. Take these last little bits here and we'll comment them out. Right-click and comment. And let's add another comment here, then we'll talk about if statements. So MATLAB handles all of its control flow and nesting with tabs. So for our if statement, let's grab some user input and test it out.
Let's create a variable called myInput, and MATLAB uses the function input to get keyboard input, and it takes a prompt argument. So let's say, please enter a number. That looks good, semicolon to close it off. And let's test our user input value. So we'll say if, and if myInput is less than zero, let's go ahead and give them a little message. We'll say display, and we'll display "You're kind of negative!" Notice I used double quotes here to define my string, which allows me to put a single quote in here, and not goober up my string.
If we want to test another case, we need to use the else if statement. So let's see if it's in a range here. We'll say if, and open close some parentheses, myInput is greater than or equal to zero, and let's combine that with an and statement here. Double ampersands, and also if myInput is less than or equal to 100, then we'll give them a different message.
We'll display, "You're right on!" Then we use the else for a catchall. So this catchall will be anything that's larger than a hundred. So we'll display here, "Whoa, that's a big number!" And then we wrap up our if statement with an end. Alright, let's go ahead and save that. And let's test it out.
We'll do my, F I, and tab to complete. And there we go, we have our request for user input. Let's start off with something negative. I'll say minus 100, and we get back, "You're kind of negative!" Great, so we've got my first script, let's try it again. Please enter a number, let's try 55. Alright, we're right on. Let's clear that screen. Press the up arrow to bring back my first script. And now let's try something really big, 20,000.
And we get, "Whoa, that's a big number!" So it looks like our if statement is working correctly.
Released
4/16/2018- Creating MATLAB variables
- Working with matrix and scalar operations
- Using if statements and loops
- Creating functions
- Importing data
- Building basic plots and 3D plots
- Working with images
- Creating Simulink models
Share this video
Embed this video
Video: If statements