Control Flow and Operators
Control Flow and Operators
OPERATORS
TOPICS
• Introduction
• Control Flow
• The ‘‘if...end’’
• Relational and logical
• Operator precedence
• Saving output to a file
INTRODUCTION
1.
discr = b*b - 4*a*c;
if discr < 0
disp(’Warning: discriminant is negative, roots are imaginary’);
end
CONTROL FLOW
2.
discr = b*b - 4*a*c;
if discr < 0
disp(’Warning: discriminant is negative, roots are imaginary’);
else
disp(’Roots are real, but may be repeated’) end
CONTROL FLOW
3.
discr = b*b - 4*a*c;
if discr < 0
disp(’Warning: discriminant is negative, roots are imaginary’);
elseif discr == 0
disp(’Discriminant is zero, roots are repeated’)
else
disp(’Roots are real’)
end
CONTROL FLOW
Note that the “equal to” relational operator consists of two equal signs (==)
(with no space between them), since = is reserved for the assignment operator.
OPERATOR PRECEDENCE
• We can build expressions that use any combination of arithmetic, relational, and
logical operators.
• Precedence rules determine the order in which MATLAB evaluates an expression.
• We have already seen this in the \Tutorial Lessons".
• The precedence rules for MATLAB are shown in this list, ordered from highest (1)
to lowest (9) precedence level.
• Operators are evaluated from left to right.
OPERATOR PRECEDENCE
Precedence Operator
1 Parentheses ()
2 Transpose (.’), power (.^), matrix power (^)
3 Unary plus (+), unary minus (-), logical negation (~)
4 Unary plus (+), unary minus (-), logical negation (~)
Multiplication (.*), right division (./), left division (.\),
matrix multiplication (*), matrix right division (/),
matrix left division (\)
5 Addition (+), subtraction (-)
6 Colon operator (:)
7 Less than (<), less than or equal to (<=), greater (>),
greater than or equal to (>=), equal to (==), not equal to (~=)
8 Element-wise AND, (&)
9 Element-wise OR, (|)
EXAMPLES:
1.) Create a MATLAB script to input a number and determine whether it is odd
or even.
2.) Create a MATLAB script to a three digit number (100 to 999) and output its
ones digit, tens digit, and hundreds digit. Display an error message if the
number entered is not three digit.