Page 42 - MATLAB an introduction with applications
P. 42
MATLAB Basics ——— 27
The general form of a simple if statement is as follows:
if logical expression
statements
end
If the logical expression is true, the statements between the if statement and the end statement are executed.
If the logical expression is false, then it goes to the statements following the end statement.
1.16.5 Nested if Statements
Following is an example of nested if statements:
if a < 30
count = count + 1;
disp(a);
if b > a
b = 0;
end
end
1.16.6 else AND elseif Clauses
The else clause allows to execute one set of statements if a logical expression is true, and a different set if the
logical expression is false.
% variable name inc
if inc < 1
x_inc = inc/10;
else
x_inc = 0.05;
end
When several levels of if-else statements are nested, it may be difficult to find which logical expressions must
be true (or false) to execute each set of statements. In such cases, the elseif clause is used to clarify the
program logic.
1.16.7 MATLAB while Structures
There is a structure in MATLAB that combines the for loop with the features of the if block. This is called the
while loop and has the form:
while logical expression
This set of statements is executed repeatedly as long as the logical expressions remain true (equals +1) or if the
expression is a matrix rather than a simple scalar variable, as long as, all the elements of the matrix remain non-
zero.
end
In addition to the normal termination of a loop by means of the end statement, there are additional MATLAB
commands available to interrupt the calculations. These commands are listed in Table 1.26.
F:\Final Book\Sanjay\IIIrd Printout\Dt. 10-03-09