10.1. Conditional statements#

Conditional statements are statements which we can use to make decisions based on its result. They return a Boolean value of either true or false depending on what condition we have applied.

Table 10.1 Conditional statements#

Operator

Description

MATLAB syntax

\(=\)

equal

x == y

\(\neq\)

not equal to

x ~= y

\(>\)

greater than

x > y

\(<\)

less than

x < y

\(\geq\)

greater than or equal to

x >= y

\(\leq\)

less than or equal to

x <= y

MATLAB can also assume a numerical value of a boolean value where 1 is the same as true and 0 is the same as false. Create a new MATLAB file called M10_If_statements.m and save it to your OneDrive folder. Enter the following code into your program.

clear % Clear all variables
clc   % Clear command window

% 10. If Statements

% Conditional statements
x = 1;
y = 2;

fprintf("\n10.1 Conditional statements\n---------------------------\n")
fprintf("%d == %d : %d \n", x, y, x == y)
fprintf("%d ~= %d : %d \n", x, y, x ~= y)
fprintf("%d > %d  : %d \n", x, y, x > y)
fprintf("%d < %d  : %d \n", x, y, x < y)
fprintf("%d >= %d : %d \n", x, y, x >= y)
fprintf("%d <= %d : %d \n", x, y, x <= y)

Run your program and your should see the following printed to the console.

1 == 2 : 0 
1 ~= 2 : 1 
1 > 2  : 0 
1 < 2  : 1 
1 >= 2 : 0 
1 <= 2 : 1