Wednesday, 8 June 2016

MATLAB Programming 29 - if...end Statement

Decision making structures require that the programmer should specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

MATLAB provides following types of decision making statements.

if... end Statement

An if ... end statement consists of an if statement and a boolean expression followed by one or more statements. It is delimited by the end 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 expression evaluates to true, then the block of code inside the if statement will be executed. If the expression evaluates to false, then the first set of code after the end statement will be executed.


Example

Create a script file and type 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\n' );
end
fprintf('value of a is : %d\n', a);

When you run the file, it displays the following result:

a is less than 20

value of a is : 10


No comments:

Post a Comment