CIE212 Programming for Civil Engineering
Example 2.1: Operator Precedence
Precedence levels determine the order in which MATLAB evaluates an expression.
Within each precedence level, operators have equal precedence and are evaluated from LEFT RIGHT
Definition of Unary and Binay Operations:
• A unary operator operates on only one operand and appears with its operand in this format: operator
operand
• A binary operator operates on two operands and appears with its operands in this format: operand1
operator operand2
Take for example: - 5 - 6 = - 11
first '-' is unary negation and the second '-' is binary subtraction.
Take another example: 3 − − 2 = 5
first '-' is binary subtraction, while the second '-' is unary negation
Related links: (1) Operator Precedence (2) Operators & Special Characters
% Example -1-
1:2 + 5
ans = 1×7
1 2 3 4 5 6 7
(1:2) + 5
ans = 1×2
6 7
% Example -2-
2 * 3 + 5
ans = 11
1
2 * (3 + 5)
ans = 16
% Example -3-
3 ^ 1/2
ans = 1.5000
3 ^ (1/2)
ans = 1.7321
% Example -4-
1:2:5'
ans = 1×3
1 3 5
(1:2:5)'
ans = 3×1
1
3
5
% Example -5-
1 + 2 * 3
ans = 7
1 + (2 * 3)
ans = 7
(1 + 2) * 3
ans = 9
% Example -6-
4 ^ 1 ^ 2
ans = 16
(4 ^ 1) ^ 2
ans = 16
4 ^ (1 ^ 2)
ans = 4
% Example -7-
2
-2 ^ 4
ans = -16
(-2) ^ 4
ans = 16
% Example -8-
1/4*5
ans = 1.2500
1/(4*5)
ans = 0.0500
% Example -9-
6*10/13 + 18/(5*7) + 5*9^2
ans = 410.1297
% Example -10-
6*35^(1/4) + 14^0.35
ans = 17.1123
% Example -11-
-5-6 % unary negation, binary subtration
ans = -11
3--2 % binary subtraction,unary negation
ans = 5
5+-2 % binary addition,unary negation
ans = 3
5---2 % binary subtraction,unary negation,unary negation
ans = 3