Conditional Execution


Recall for loops

for k = randperm(4)
    fprintf('k = %d, ', k)
    k = 7;
end
fprintf('\n')

Boolean values

 

 


Relational operators

Operators:    ==   ~=   <   <=   >   >=

 


Logical operators

Operators:    ~   &   &&   |   ||

& and |

 

&& and ||

 

 

 

 

 

 

 

 


Selection using if

Basic if statement

if boolean_condition
    statements to execute if boolean_condition is true
end

Example:

if 'A' < 'a' && ~('z' < 'Z')
    disp('ASCII values for upper-case come before lower-case')
end

if-else statement

if boolean_condition
    statements to execute if boolean_condition is true
else
    statements to execute if boolean_condition is false
end

Example:

if '3' + '4' == '7'
    disp('character addition works')
else
    disp('character addition does not work')
end

if-elseif-else statement

if bool_cond1
    statements to execute if bool_cond1 is true
elseif bool_cond2
    statements to execute if bool_cond2 is true
elseif bool_cond3
    statements to execute if bool_cond3 is true
else
    statements to execute if none of the boolean conditions is true
end

Example:

choice = input('Enter yes, no, or maybe: ', 's');

if length(choice) == 3 && (choice(1) == 'y' || choice(1) == 'Y')
    disp('you chose "yes"')
elseif length(choice) == 2 && (choice(1) == 'n' || choice(1) == 'N')
    disp('you chose "no"')
elseif length(choice) == 5 && (choice(1) == 'm' || choice(1) == 'M')
    disp('you chose "maybe"')
else
    disp('unknown choice')
end

 


Iteration using while loop

while boolean_condition
    statements to execute if boolean_condition is true
end

Example: count how many rolls it takes in order to get 10 3's.

 

 

 

 

 

 

 

 

 

 

 


for vs while vs if

for loop

for x = 5 : 10
    disp(x)
end
disp(x)

while loop

x = 5;
while x <= 10
    disp(x)
    x = x + 1;
end
disp(x)

if statement

x = 5;
if x <= 10
    disp(x)
    x = x + 1;
end
disp(x)

Vectors and conditional execution

Relational operators and vectors/matrices

vec1 = [2, 5, 7, 9];
vec2 = [1, 8, 7, 3];
v1_eq_v2 = vec1 == vec2;
v1_neq_v2 = vec1 ~= vec2;

choice = input('Enter yes, no, or maybe: ', 's');

if choice == 'yes'
    disp('you chose "yes"')
end

 

 

 

 

 

 

 

 

Useful MATLAB commands:

Operation on strings

str1 = 'hello';
str2 = 'world';
str3 = 'CS 368';
str4 = 'World';

 

 

 

 

Useful MATLAB commands: