Conditional Statements allow us to perform more purposeful scripting. They allow us to compare numbers, strings, variables, etc and execute code based off of the conditions met.
Let's first start by looking at an if statement.
matlab
num = 4;
if num > 2
disp("num is greater than 2");
end
What is happening in the code example above is if the variable 'num' is greater than 2, the string "num is greater than 2" is printed to the Command Window.
You see, the first step of the if statement is it makes the comparison, is 'num' greater than 2. Now remember from the Boolean variables tutorial, we talked about how logical operators output a 1 if they pass. What the if statement does is it determines if a 1 is returned from all of the logical conditions. If so, then the code after is executed.
Note: all if statements should have an 'end' to indicate where the if statement ends. If an 'end' is not present, then an error will occur.
Now, what if our initial condition is not true and does not return a 1? Well, then we use what's called an else statement to execute code if the first condition fails.
matlab
num = 4;
if num < 4
disp("num is less than 4");
else
disp("num is not less than 4");
end
In the code, since 4 is not less than 4, it is equal to, the first condition fails! Then the else condition is executed. Now we can run code if our initial statement does not pass.
Now let's say we want to condition multiple times. Then, an elseif statement can be used. Here's how!
matlab
num = 5;
if num > 5
disp("num is greater than 5");
elseif num < 5
disp("num is less than 5");
else
disp("num is equal to 5");
end
In the example above, since num is equal to 5, it does not pass the first or second statement, so that means it is equal to 5. There is no limit to the number of elseif statements, but there can only be one if and one else statement.