Professional Documents
Culture Documents
Lecture 7. Flow Control
Lecture 7. Flow Control
𝑖𝑓 𝑥 > 10 % 𝑥 𝑖𝑠 𝑠𝑐𝑎𝑙𝑎𝑟
𝑦 = 2 ∗ 𝑥 + 5
𝑒𝑙𝑠𝑒
𝑦 = 𝑥^2 / 5
𝑒𝑛𝑑
1
Advanced Computers: MATLAB Lecture 7: Flow Control
𝑖𝑓 𝑥 > 10 % 𝑥 𝑖𝑠 𝑠𝑐𝑎𝑙𝑎𝑟
𝑦 = 2+𝑥/5
𝑖𝑓𝑒𝑙𝑠𝑒 𝑥 > 5
𝑦 = 2∗𝑥/5
𝑒𝑛𝑑
Furthermore, an if structure can have more than one elseif block.
Therefore, the if structure can be used in many different possible forms:
𝑖𝑓 … 𝑒𝑛𝑑
𝑖𝑓 … 𝑒𝑙𝑠𝑒 … 𝑒𝑛𝑑
𝑖𝑓 … 𝑒𝑙𝑠𝑒𝑖𝑓 … 𝑒𝑛𝑑
𝑖𝑓 … 𝑒𝑙𝑠𝑒𝑖𝑓 … 𝑒𝑙𝑠𝑒 … 𝑒𝑛𝑑
𝑖𝑓 … 𝑒𝑙𝑠𝑒𝑖𝑓 … 𝑒𝑙𝑠𝑒𝑖𝑓 … 𝑒𝑛𝑑
𝑖𝑓 … 𝑒𝑙𝑠𝑒𝑖𝑓 … 𝑒𝑙𝑠𝑒𝑖𝑓 … 𝑒𝑙𝑠𝑒 … 𝑒𝑛𝑑
3. for Structure
The for structure executes commands a predetermined number of times.
The general syntax of for structure is:
𝑓𝑜𝑟 𝑖𝑛𝑑𝑒𝑥 = 𝑠𝑡𝑎𝑟𝑡 ∶ 𝑖𝑛𝑐𝑟𝑒𝑚𝑒𝑛𝑡 ∶ 𝑙𝑎𝑠𝑡
𝑐𝑜𝑚𝑚𝑎𝑛𝑑 𝑙𝑖𝑛𝑒𝑠
𝑒𝑛𝑑
The values of start, increment, and last can be positive or negative values.
On each iteration, index is incremented, or is decremented, by the value increment.
For positive increment, execution terminates when the value of the index exceeds the
last value;
For example,
𝑠 = 0
𝑓𝑜𝑟 𝑡 = 1: 3: 16
𝑠 =𝑠+𝑡∗8
𝑒𝑛𝑑
2
Advanced Computers: MATLAB Lecture 7: Flow Control
Practical Examples
Script 7.1. Write a script for computing the following equations of 𝑦 when 𝑥 = 20, 8, 1, or
154.
𝑥
− 4 ; 100 ≤ 𝑥
100
𝑥
+ 4 ; 10 < 𝑥 < 100
10
𝑦= 𝑥
× 4 ; 5 < 𝑥 ≤ 10
5
𝑥2
{ 5 − 4 ; 𝑜𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒
Script:
𝑥 = 20
𝑖𝑓 𝑥 > 100
𝑦 = 𝑥 / 100 − 4
𝑖𝑓𝑒𝑙𝑠𝑒 𝑥 > 10
𝑦 = 4 + 𝑥 / 10
𝑖𝑓𝑒𝑙𝑠𝑒 𝑥 > 5
𝑦 = 4∗𝑥/5
𝑒𝑙𝑠𝑒
𝑦 = 𝑥^2 / 5 − 4
𝑒𝑛𝑑
Rerun:
3
Advanced Computers: MATLAB Lecture 7: Flow Control
𝑥 = 8
𝑥 = 1
𝑥 = 154
Script 7.2. Write a script for computing 𝑦 = 2𝑥 + 3 for 𝑥 = 1. .15 .
Script:
𝑓𝑜𝑟 𝑥 = 1: 15
𝑦 =2∗𝑥+3
𝑒𝑛𝑑
Script 7.3. Let a vector 𝑥 of values −10 . . 5. Write a script for computing the values of vector
𝑦 where 𝑦𝑖 = 2𝑥𝑖 + 3 for 𝑖 = 1. .15 .
Script:
𝑥 = −10: 5
𝑓𝑜𝑟 𝑘 = 1: 15
𝑦(𝑘) = 2 ∗ 𝑥(𝑘) + 3;
𝑒𝑛𝑑
𝑦