An interactive introduction to MATLAB

(Jeff_L) #1

48 decision making


b) w=v
c)v < w+v
d) (v < w) +v

4.2 The if-else statement


The if,else, and elseifstatements inMATLAB provide methods of
controlling which parts of your code should execute based on whether certain
conditions are true or false. The syntax of the simplest form of anifstatement
is given in Listing 4.4.
Listing 4.4: Syntax of anifstatement
1 iflogical_expression
2 statements
3 end

Comments:


  • Line 1 contains theifcommand, followed by an expression which must
    return true or false.

  • Line 2 contains the body of theifstatement which can be a command or
    series of commands that will be executed if the logical expression returns
    true.

  • Line 3 contains theendcommand which must always be used to close
    theifstatement.

  • If the logical expression returns trueMATLABwill execute the state-
    ments enclosed betweenifandend. If the logical expression returns
    falseMATLABwill skip the statements enclosed betweenifandend
    and proceed with any following code.


Listing 4.5 presents a very simple example of using anifstatement to test if
a user has entered a number greater than 10.
Free download pdf