Matlab Lec#5
Matlab Lec#5
Lect#5
SZIC
Control Statement
▰ They allow you to make decisions and control the order in which
statements are executed.
▰ The "if" statement allows you to execute a block of code only if a specified condition
is true.
▰ This is useful when you want your program to take different actions based on
whether a condition is true or false for example…..
x=1;
x = 10; y=8;
if x > 0 if x>8
disp('x is positive’); disp('greater tan
else 7')
disp('x is non-positive'); else
end disp('less then 8')
end
Example 1
x = 10;
y = 5;
if x > y
disp('x is greater than y');
if x > 0
disp('x is positive');
else
disp('x is non-positive');
end
else
disp('y is greater than or equal to x');
end
Example 3
• Loops in MATLAB
• Repeats commands until a condition is met or a
specified number of iterations are completed.
• Types of Loops
• While loops
• For loops
• Nested loops
While Loop
While Loop
Syntax
while condition
% commands
end
While Loop Flow Chart….
Flowchart Section:
1. Start
2. Initialization: Label: Initialize num = 20
3. Condition Check: Label: num < 30?
4. Commands: Label: Display num, Increment num by 1
5. Update: Label: Update num
6. Terminate: Label: End
While Program
num = 20;
while (num < 30)
disp(['value of num: '
num2str(num)]);
num = num + 1;
end
For Loop Syntax
Syntax
for initial value:step value:final-value
statements
end
or
for initial value:final value
statements
end
For Loop
Flowchart
Nested Loops
Syntax
for i = start1:increment1:end1
for j = start2:increment2:end2
% commands
end
end