Flow Control

Introduction

Different loops can be used in MATLAB such as:
If-else statement
Switch and case statement
For loop
While loop

If-else statement

1. “if” statement evaluates a logical expression and executes a group of statements when the expression is true.
2. The optional “elseif” and else keywords provide for the execution of alternate groups of statements.
3. An “end” keyword, which matches the “if”, terminates the last group of statements.
4. The groups of statements are delineated by the four keywords- no braces or brackets are involved.
The general syntax is as follows:
if expression1
statements1
elseif expression2
statements2
else
statements3
end
Example :

Note that “if n==5” is used and not “if n=5”
If A and B are scalars only then “if A == B, …” works, but if A and B are matrices this might not work as expected.

Operators

Switch and Case statement

1. “switch” statement executes a group of statements based on the value of a variable or expression.
2. The keywords case and otherwise delineated the groups.
3. Only the first matching case is executed.
4. There must always be an end to match the switch.
The general syntax is as follows:
switch variable
case case_value1
statements1
case case_value2
statements2

otherwise
statements
end
Example :

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s