MATLAB Decision Making
In this section: Learn about the types of decisions MATLAB provides and use them for decision making.
What is the decision structure used for? Decision structure requires the programmer to use one or more conditions to evaluate or test the program, execute along one or more statements, and continue execution if the condition is determined to be true; if the condition is determined to be false (false ), execute other statements to be executed.
The following diagram is a typical decision structure, which is the general form of most programming languages:
The decision types provided by MATLAB are shown in the following table. Click on the links to view the functions of each decision type:
statement | describe |
---|---|
if ... end statement | An if...end statement consists of a Boolean expression followed by one or more statements. |
if...else...end statement | An if statement can be followed by an optional else statement which will be executed if the boolean expression is false. |
If... elseif...elseif...else...end statements | An if statement can be followed by one (or more) optional elseif... and an else statement, which is useful for testing various conditions. |
nested if statements | You can use one if or elseif statement inside another if or elseif statement. |
switch statement | A switch statement allows variables to be tested for equality against a list of values. |
nested switch statements | You can use a switch statement inside another switch statement . |
MATLAB if...end statement
An if statement and a Boolean expression followed by one or more statements, separated by end statements, is an if...end statement
MATLAB if statement syntax
The syntax of an if statement in MATLAB is:
if <expression> % statement(s) will execute if the boolean expression is true <statements> end
If the evaluation result of the expression is "true", then in the code block, the if statement will be executed. If the expression evaluates to "false", the statements after the first set of code will be executed.
MATLAB if statement flow chart:
Detailed examples are as follows:
Create a script file in MATLAB and enter the following code:
a = 10; % check the condition using if statement if a < 20 % if condition is true then print the following fprintf('a is less than 20 ' ); end fprintf('value of a is : %d ', a);
Running the file yields the following results:
a is less than 20 value of a is : 10