Lecture 2
Lecture 2
OBJECTIVES
1
9/8/2022
CONTENTS
• Function
• if/else Structure
• switch structure
• for loop
• while loop
• Improving the efficiency of the loop
• Break and continue
• Tic toc
• Nested loop
M-File
Live script
2
9/8/2022
subplot(m,n,p)
hold on
hold off
Function File
The velocity of a free-falling bungee jumper can be computed
3
9/8/2022
IF STRUCTURE (CASE 1)
if statement has the following form:
if comparison
statements
end
If the comparison is true, the statements between the if statement and the end
statement are executed. If the comparison is false, the program jumps
immediately to the statement following end .
G = input('G is equal to:')
if G>50
disp('pass')
end
4
9/8/2022
10
5
9/8/2022
SWITCH STRUCTURE
switch/case structure is often used when a series of programming path options exists for a given
variable, depending on its value.
city = input('To know the Apartment rent, please, enter the name of the city in single quotes : ');
switch city
case 'dammam'
disp('$250')
case 'jeddah'
disp('$150')
case 'makkah'
disp('300')
otherwise Note
disp('Not on file') case '---'
end
11
FOR LOOP
The structure of a for loop can be summarized as
for index = start:finish
How often will the
commands to be executed loop run?
end
6
9/8/2022
i = 0;
Container
for t2= 0:0.02:50 t1 = 0:0.02:50;
i = i + 1; y1 = cos(t1);
y2(i) = cos(t2);
end
13
WHILE LOOPS
While loops are similar to for loops. The big difference is the way MATLAB ®
decides how many times to repeat the loop. While loops continue until some
criterion is met.
while condition
commands to be executed
end
k = 0;
while k<3 for k=1:3
k = k+1; disp(k)
disp(k) end
end
In this case, we initialize a counter, k ,
OR !! before the loop. Then the loop
while k<3 repeated as long as k was less than 3.
disp(k) Is it working ??
end
14
7
9/8/2022
s = [76,45,98,97]; s = [76,45,98,97];
c = 0; c = 0;
k = 0; counter
for k=1:length(s) while k<length(s)
k = k+1; counter = 1+ counter
if s(k)>90 if s(k)>90
c = c + 1; c = c + 1;
end end
end end
disp(c) disp(c)
15
NESTED LOOPS
If & for loops can be nested inside each other. The main point to note is that the index of the
inner for moves faster.
16
8
9/8/2022
17
tic
i = 0;
for t = 0:0.01:10
i = i + 1;
y(i) = sin(t);
end
toc
tic
t = 0:0.01:10;
y = sin(t);
toc
18
9
9/8/2022
13
19
14
20
10