Conditional Statements Matlab Help

Conditional Statements
In everyday language we describe our decision making by using conditional phrases such as.If I get a raise, I will buy a new car. If the statement, I get a raise, is true, the action indicated (buy a new car) will be executed. Here is another example: If I get at least a $100 per week raise, I will buy a new car; else, I will put the raise into savings. A slightly more involved example is: If I get at least a $100 per week raise, I will buy a new car; else, if the raise is greater than $50, I will buy a new stereo; otherwise, I will put the raise into savings.

We can illustrate the logic of the first example as follows:

If I get a raise, I will buy a new car . (period)

Note how the period marks the end of the statement.

The second example can be illustrated as follows:

If I get at least a $100 per week raise, I will buy a new car;

else,

I will put the raise into savings (period)

The third example follows.

If I get at least a $100 per week raise, I will buy a new car;

else, if the raise is greater than $50, I will buy a new stereo; otherwise,

I will put the raise- into savings . (period)

The MATLAB conditional statements enable us to write programs that make decisions. Conditional statements contain one or more of the if, else, and else if statements. The end statement denotes the end of a conditional statement. just as the period was used in the preceding examples. These  conditional statements have a form similar to the examples, and they read somewhat like their English-language equivalents.

The if Statement
The if  statement’s basic form is
if logical expression
statements
end

Every if statement must have an accompanying end statement. The end statement marks the end of the statements that are to be executed if the logical expression is true. A space is required between the if and the logical expression, which may be a scalar, a vector, or a matrix.

For example, suppose that x is a scalar and that we want to compute y = only if x O. In English, we could specify this procedure as follows: If x is greater than or equal to zero, compute y from y =  The following if  statement implements this procedure in MATLAB assuming x already has a scalar value.

if x >= 0
y = sqrt (x)
end

If x is negative, the program takes no action. The logical expression here is x >= 0, and the statement is the single line y = sqrt (x) .
The if structure may be written on a single line; for example:
if x >= 0, Y = sqrt (x), end
However, this form is less readable than the previous form. The usual practice is to indent the statements to clarify which statements belong to the if and its corresponding end and thereby improve readability.
The logical expression may be a compound expression; the statements may be a single command or a series of commands separated by commas or semicolons or on separate lines. For example if x and y have scalar values:

Z =’,O;,w = 0;
if (x >= O)&(y >= 0)
, z ‘= sqrt(x) + sqr t Iy l ,
W = log (x) – 3*log(y)
end

The values of z and w are computed only if both x and y are non-negative. Otherwise, z and w retain their values of zero. The flowchart is shown in Figure 4.4-1.
We may “nest” if statements, as shown by the following example.
if logical expression 1
statement group 1
if logical ‘expression 2
statement group 2
end
end

Note that-each if statement has an accompanying end statement.

The else Statement
When more than one action can occur as a result of a decision, we can use the else and elseif statements along with the if statement. The basic structure

Flowchart 'corresponding to the pseudocode example

Flowchart ‘corresponding
to the pseudocode example

for the use of the else statement is
if logical expression
statement group 1
else
statement group 2
end
Figure 4.4-2 shows the flowchart of this structure;
For example, suppose that y = √ x for x ≥ 0 and that y = ex – 1 for x < O. The following statements will calculate y, assuming that x already, has a scalar value.
if x>= 0
y = sqrt (x)
else
y = exp(x) – l’
end

Flowchart of the e 1 s e structure.

Flowchart of the e 1 s e structure.

When the test, if logical expression, is performed, where the logical expression may be an array, the test returns a value of true only if all the elements of the logical expression are true! For example, if we fail to recognize how the test works, the following statements do not perform the way we might expect.

x= [4,-9,25];
if x < 0
disp(‘Some of the,elements of x are negative.’)
else
y = sqrt(x)
end

When this program is run it gives the result

y =
2  0 + 3.000i 5

The program does not test each element in x in sequence. Instead it tests the truth of the vector relation x < O. The test if x < 0 returns a false value because it generates the vector [0, 1 , 0 ] . Compare the preceding program with the following program.

x = [4,-9,25];
if x >= 0
y = sqrt(x)
else
disp {‘Some of the elements of x are negative.’)
end

When executed, it produces the following result: Some of the elements of x are negative. The test if x < O is false,and the test if x >= 0 also returns a false value because x >= 0 returns the ‘vector [1,0,1].

We sometimes must choose between a program that is concise, but perhaps more difficult to understand, and one that uses more statements than is necessary. For example, the statements

if logical expression 1
if logical expression 2
statements
end
end
can be replaced with the more concise program
if logical expression 1 & logical expression 2
statements
end

The elseif Statement
The general form of the if statement is
if logical expression 1
statement group 1
elseif logical expression 2
statement group 2
else
statement group 3
end

The else and else if statements may be omitted if not required. However, if both are used, the else statement must come after the else if statement to take care of all conditions that might be unaccounted for. Figure 4.4-3 is the flowchart for the general i f structure.

For example, suppose that y = In x if x ~ 5 and that y = .j X if 0 :::x < 5. The following statements will compute y if x has a scalar value.

if x >= 5
y = log (x)

Flowchart for the general i f structure.

Flowchart for the general i f structure.

else
if x >= 0
y = sqrt(x)
end
end
If x = -2, for example, no action’ will be taken. If we use an e 1 s e if.we need fewer statements. For example:
if x >= 5·
y = log (x)
elseif x >= 0
y = sqrt(x)
end
Note that the elseif statement does not require a separate end statement.
The else statement can be used with elseif to create detailed decision-making programs. For example. suppose that y = In x for x > 10. y = √ x for 0 ≤ x ≥ 10, and y = ex – 1 for x < O.The following statements will compute y if x already has a scalar value.

if x > 10
y = log (x)
elseif x >= 0
y = sqrt (x)
else
y exp(x) – 1
end

Decision structures may be nested; that is, one structure can contain another structure, which in turn can contain another, and so on. The flowchart in Figure 4.4-4 describes the following code, which contains an example of nested if statements and assumes that x already has a scalar value

Flowchart illustrating nested i f statements

Flowchart illustrating nested i f statements

if x > 10
y = log (x)
if y >= 3
z = 4*y
elseif y >= 2.5
z 2*y
else
z  = 0
end
else
y 5*x
z 7*x
end
Note how the indentations emphasize the statement groups associated with each end statement. The flowchart required to represent this code is quite large. In practice, flowcharts often must be condensed by omitting some details to effectively describe the overall program.

Test Your Understanding
T4.4-1 Enter the script file whose flowchart is shown in Figure 4.4-4. Run the file for the following values of x. Check the program results by hand: x = 11,25,2,13.
T4.4-2 Given a number x and .the quadrant q (q = 1,2,3,4), write a program . to compute sin-1(x) in degrees, taking into account the quadrant. The program should display an error message if Ix I > 1 .

Checking the Number of Input and Output Arguments
Sometimes you will want to have a function act differently depending on how many inputs it has: You can use the function nargin, which stands for “number of input arguments.” Within the function you can use conditional statements to direct the flow of the computation depending on how many input arguments there are. For example, suppose you want to compute the square root of the the input if there is only one, but compute the square root of the average if there are two inputs. The following function does this.
function z = sqrt fun(x, y)
if (nargin == 1)
z = sqr t Ix l :
elseif (nargin == 2)
z = sqrt((x + y)/2)i
end’

The nargout function can be used to determine the number of output arguments.

Strings and Conditional Statements
A string is a variable that contains characters. Strings are useful for creating input prompts and messages and for storing and operating on data such as names and addresses. To create a string variable, enclose the characters in single quotes. For example, the string variable name is created as follows:
»name = ‘Leslie Student
name =
Leslie Student
The following string, number
»number = ‘123’
number =
123

is not the same as the variable number created by typing number = 123. Strings are stored arrow vectors in which each column represents a character. For example, the variable name has 1 row and 14 columns (each blank space occupies one column). Thus
.»size (name)
ans =
1 14
We can access any column the way we access any other vector, For example, the letter S in the name Leslie Student occupies the eighth column in the vector name. It can be accessed as follows:
»name(8)
ans
S
The colon operator can be used with string variables as well. For example:
»first_name = name(1:6)
first_name =
Leslie
We can manipulate the columns of string variables just as we do vectors. For
example, to insert a middle initial, we type •
»full_name = [name(1:6),’ C.’ ,name(7:14)]
full_name =
Leslie C. Student
»full_name(8) = ‘F’
full_name =
Leslie F. Student

The findstr function (which stands for find string) is useful for finding the locations of certain characters. For example:
»findstr(full_name, ‘e’)
ans =
2 6 15

This session tells us that the letter e occurs in the 2nd, 6th, and 15th columns.
Two string variables are equal if and only if every character is the same, including blank spaces. Note that uppercase and lowercase letters are not the same. Thus the strings’ Hello’ and’ hello’ are not equal, and the  strings’ can not’ and’ cannot’ are not equal. The function strcmp (for string compare) determines whether two strings are equal. Typing strcmp (‘stringl’ , ‘string2′ )returns a 1 if the strings’ stringl’ and’ string2′ are equal and 0 otherwise. The functions lower (‘string’ )and upper (‘string’ ) convert’ string’ to all lowercase or all uppercase letters. These functions are useful for accepting keyboard input without forcing the user to distinguish between
lowercase and uppercase.

One of the most important applications for strings is to create input prompts and output messages. The following prompt program uses the is empty (x) function, which returns a 1 if the array x is empty and 0 otherwise. It also uses the input function, whose syntax is

x = input(‘prompt’, ‘string’)

This function displays the string prompt on the screen, waits for input from the keyboard; and returns the entered value in the string variable x. The function return empty matrix if you press the Enter key without typing anything.

the following prompt program is a script file that allows the user to answer Yes by typing either Y or y or by pressing the Enter key. Any other response is treated as a No answer.

response = input(‘Do you want to continue? Y/N [y⌉ : ‘,’s’);

if (is empty (response)) I (response == ‘y’) I (response == ,y, )

response = ,y,

else

response = N

and

Many more string functions are available in MATLAB. Type heIp  strfun to obtain information on these.

Posted on July 27, 2015 in Programming with MATLAB

Share the Story

Back to Top
Share This