An interactive introduction to MATLAB

(Jeff_L) #1

50 decision making


executed if all the logical expressions for the precedingelseifandif
commands return false.

Listing 4.7 presents a simple of example of decision making using theif,else,
andelseiffunctions. Copy and paste the example into a new script file, and
run it to see the results for yourself.
Listing 4.7: number_test.m - Script to test sign and magnitude of numbers
1 % number_test.m
2 % Script to test sign and magnitude of numbers
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<0 % Test if x is negative
14 disp('Your number is a negative number')
15 elseif x<100 % Otherwise test if x is less than 100
16 disp('Your number is between 0 and 99')
17 else % Otherwise x must be 100 or greater
18 disp('Your number is 100 or greater')
19 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 Lines 14, 16, and 18 thedispcommand is used, which simply displays
    text to the Command Window.

Free download pdf