An interactive introduction to MATLAB

(Jeff_L) #1
4.2the if-else statement 49

Listing 4.5: basic_if.m - Script to show simple if statement
1 % basic_if.m
2 % Script to show simple if statement
3 %
4 % Craig Warren, 08/07/2010

6 % Variable dictionary
7 % x Variable to hold entered number

9 clear all; % Clear all variables from workspace
10 clc; % Clear command window


12 x = input('Enter a number: '); % Get a number from the user
13 if x>10 % Test if x is greater than
14 disp('Your number is greater than 10')
15 end


Comments:


  • On Line 12 theinputcommand is used, which prompts the user for input
    with the requestEnter a number:and assigns the number entered to
    the variablex.

  • On Line 13 anifstatement is used with the logical expressionx>10. If this
    expression is true then the textYour number is greater than 10is
    displayed, otherwise if the expression is false nothing is executed.


Theelseandelseifcommands can be used to apply further conditions
to theifstatement. Listing 4.6 presents the syntax of these commands.
Listing 4.6: Syntax of anifstatement withelseandelseif
1 iflogical_expression
2 statements
3 elseif logical_expression
4 statements
5 else
6 statements
7 end

Comments:


  • On Line 3 the logical expression associated with theelseifcommand
    will only be evaluated if the preceding logical expression associated with
    theifcommand returns false.

  • Notice that the elsecommand on Line 5 has no associated logical
    expression. The statements following theelsecommand will only be

Free download pdf