FLOW CONTROL AND LOOPS (ITERATION):
Loop or iteration are useful for execution of the sequence more than once of the given statements. Basically their two types of loop forms they are: while loops and for loops. Main different between these two loops is how repetition took place in both while and for loops. While loop is used when how many times you want the loop to execute it is done based on the given condition. When going to for loop the number of repetition are given before the loop start execution.
WHILE LOOP:
While loop executes the group of statements are statement indefinite number of times until the logic condition become true. Syntax of while loop:
While expression
Statements
end
For example, suppose you wanted to double the number 2 over and over again until you got to a number over 1,000,000
number = 2;
counter = 1;
while number <= 10^6
number = 2*number;
counter = counter + 1;
end
FOR LOOP:
For loop is used for execution of group of statements or a statement for predefined number of times. Syntax of for loop.
For index = start: increment: end
Statements
End
Where index is the loop control variable
For example
s = 0;
For i = 1:10 %increment of 1
s = s + i;
End
disp(s);
FLOW CONTROL:
IF, ELSE AND ELSEIF:
If statements evaluate the logical expression and execute the group of statements when the expression is true, otherwise for execution of alternate statements it go with else or else if. An end keyword, which matches the if, terminates the last group of statements. If the logical expression is true (1), MATLAB executes all the statements between the if and end lines. It resumes execution at the line following the end statement. If the condition is false (0), MATLAB skips all the statements between the if and end lines, and resumes execution at the line following the end statement. Syntax of if condition.
if logical_expression
Statements
End
The else if statement has a logical condition that it evaluates if the preceding if (and possibly elseif condition) is false (0). The statements associated with it execute if its logical condition is true (1). You can have multiple elseifs within an if block. Syntax of elseif condition.
if expression
Statements
elseif expression
Statements
else
Statements
end
x = rand;
if x < 1/3
disp(‘x < 1/3’);
else if x < 2/3
disp(‘1/3 <= x < 2/3’);
else
disp(‘2/3 <= x ’);
end