# Programming in MATLAB¶

## Relational and logical operators¶

A relational operator compares two numbers by determining whether a comparison statement is true or false. If the statement is true, it is assigned a value of 1, and a value of 0 otherwise.

### Relational Operators¶

• < less than
• > greater than
• <= less than or equal to
• >= greater than or equal to
• == equal to
• ~= not equal to

Note that the equal to relational operator consists of two = signs (with no space between them), since one = sign is the assignment operator.

• Relational operators are used as arithmetic operators within a mathematical expression:

>> a = 5<10
a =
1
>> y=(6<=7)+(5*3==4)
y =
1

• If two scalars are compared, the result is a scalar 1 or 0. If two arrays are compared (only arrays with the same size can be compared), the comparison is done element-wise, and the result is a logical array of the same size with 1’s and 0’s according to the outcome of the comparison of each address:

>> b=[15 3 4 19 0];c = [12 32 0 -1 1];
>> b <= c

ans =
0     1     0     0     1

>> c >= 0

ans =
1     1     1     0     1

• The results of a relational operation with vectors, which are vectors with 0’s and 1’s, are called logical vector and can be used for addressing vectors. When it is for addressing another vector, it extracts from that vector the elements in the positions where the logical vector has 1’s. For example:

>> x = [-2 4 -5 6]; y = [2 2 -5 -2];
>> t = x>= 0

t =

0     1     0     1

>> y(t)

ans =

2    -2

• Order of precedence: In a mathematical expression that includes relational and arithmetic operations, the arithmetic operations (+,-,*,/,\) hav precedence over relational operations. The relational operators themselves have equal precedence and are evaluated from left to right. Parentheses can be used to alter the order of precedence. For example:

>> 3+4<16/2

ans =
1

>> 3+(4<16)/2

ans =
3.5000


### Logical Operators¶

• & AND operates on two operands (A and B). If both are true, the result is true (1) and false (0) otherwise
• | OR operates on two operands (A and B). If either one, or both are true, the result is true (1), otherwise (both are false) the result is false (0)
• ~ NOT operates on one operand. It gives the opposite of the operand.

Logical operators have numbers as operands. A nonzero number is true, and a zero number is false. Logical operations can be used with scalars and arrays (like relational operators). The following are some examples:

>> [3 4 1]&[0 -1 2]

ans =
0     1     1

>> [2 0 -1]|0

ans =
1     0     1

>> ~([-1 2 3]+[1 4 3])

ans =
1     0     0


### Order of precedence¶

Arithmetic, relational, and logical operators can all be combined in mathematical expressions. When an expression has such a combination, the result depends on the order in which the operations are carried out. The following is the order used by MATLAB:

1. (highest) Parenthese
2. Exponentiation
3. Logical NOT (~)
4. Multiplication, division
6. Relational operators (>,<,>=,<=,==,~=)
7. Logical AND (&)
8. (lowest) Logical OR (|)

The following are examples of using arithmetic, relational and logical operators:

>> x = -3; y = 6;
>> -5 < x < -2

ans =
0


The above inequality is mathematically correct, but the answer is FALSE since MATLAB executes from left to right. First, -5 < x is true (=1) and then 1 < -2 is false (0). The correct statement in MATLAB is obtained by using & operator as follows:

>> -5 < x & x  < -2

ans =
1


The two inequalites are executed first. Since both are true (1), the answer is 1.

### Built-in Logical Functions¶

MATLAB has built-in functions that are equivalent to the logical operators. These functions are:

Functions Description
and(A,B) equivalent to A&B
or(A,B) equivalent to A|B
not(A) equivalent to ~A

Some more important built-in functions are as follows.

• xor(a,b): Exclusive or. It returns true (1) if one operand is true and the other is false

• all(A) returns 1 if all elements of a vector A are nonzero and returns 0 if one or more elements are zero. If A is a matrix, treats a columns of A as vectors, and returns a vector with 1’s and 0’s.

• any(A) returns 1 if any element of a vector A is nonzero and returns 0 if all elements are zero. If A is a matrix, treats columns of A as vectors.

• find(A): If A is a vector, returns the indices of the nonzero elements:

>> A = [-1 2 0 3 0 1]; find(A)

ans =
1     2     4     6


The command find(A > 1) returns the indices of the elements that are larger than 1 (and we can use any relational operator). For example:

>> find(A == 0)

ans =
3     5


The find command is useful for extracting the elements of a vector that satisfy some desired condition. For example, to select the nonnegative entries of A, we can type:

>> A(find( A >= 0))

ans =
2     0     3     0     1


or we can directly use:

>> A(A >= 0)

ans =
2     0     3     0     1


## Conditional Statements¶

A conditional statement is a command that allows MATLAB to make a decision of whether to execute a group of commands that follow the conditional statement, or to skip these commands. The basic form of a conditional statement is:

if CONDITIONAL STATEMENT


CONDITIONAL STATEMENT consists of relational and/or logical operators. For example:

if x <= 2
if x == 4
if (x >= y)|(z == 3)


If the CONDITIONAL STATEMENT is true, a group of commands that follow the statement is executed, and skips the commands otherwise.

### The if structure¶

The if construct has the form:

if CONDITIONAL_STATEMENT1
expression 1
expression 2
...
elseif CONDITIONAL_STATEMENT2
expression 1
expression 2
...
else
expression 1
expression 2
...
end

• The conditional statements are logical expressions that control the operation of if construct.
• If CONDITIONAL_STATEMENT1 is true (returns 1 when it is non-zero), then the program executes the expressions in the first block and skips to the end.
• Otherwise, the program checks for the result of CONDITIONAL_STATEMENT2. If it is true, then the program executes the expressions in the second block and skips to the end.
• If all conditional statements return zero (false), then the program executes the expressions in the block associated with the else clause.
• There can be any number of elseif clauses (0 or more) in an if construct, but there can be at most one else clause.
• If all conditional statements are false, and there is no else clause, then the program skips to the end without executing any part of the if construct.
• Note that the keyword end in this contruct is completely different from the MATLAB function end we use for indexing arrays (to return the last entry of a vector). MATLAB can tell the difference the two usages of end from the context.

As an example, consider the solution of a quadratic equation of the form

The solution of this equation is

Therefore, if , then there are two distinct real roots. If , then there are two repeated roots, and if , then there are two complex roots to the quadratic equation.

Hence, given values of , we can determine the characteristic of the two roots using if stucture by:

D = b^2-4*a*c;

if D > 0
disp('This equation has two distinct real roots');
elseif D == 0
disp('This equation has two identical real roots');
else
disp('This equation has two complex roots.');
end


It is also possible to implement an algorithm using nested if statements. We will show the usage of nested if by an example.

Suppose we are writing a code that reads in a numerical grade and assigns a letter grade according to this policy:

There are two possible methods for assigning a letter grade using if structure. The first method is using multiple elseif clauses:

grade = 80; % example
else
end


The second approach is to use nested if clauses:

grade = 80;
else
else
else
else
end
end
end
end


It is evident from the above example that if there are a lot of mutually exclusive options, a single if construct with multiple elseif clauses will be simpler than a nested if construct.

### The switch construct¶

The switch construct is another form of branching construct. It selects a particular code block to execute based on the value of a single integer, character, or logical expression. The general form of a switch construct is:

switch SWITCH_EXPRESSION
case CASE_EXPR1
code 1
code 2
...
case CASE_EXPR2
code 1
code 2
...
otherwise
code 1
code 2
...
end

• If the value of SWITCH_EXPRESSION is equal to CASE_EXPR1, then the first code block will be executed, and the program will jump to the end. The same idea applies for any other cases in the construct.

• The otherwise is optional. If it is present, it will be executed whenever the value of SWITCH_EXPRESSION is outside the range of all the case selectors. If it is not present, and the value of SWITCH_EXPRESSION is outside the range of all cases, then none of the code blocks will be executed.

• If many values of the SWITCH_EXPRESSION should cause the same code to execute, all of these values many be included in a single block by enclosing them in brackets:

switch SWITCH_EXPRESSION
case {CASE_EXPR1, CASE_EXPR2, CASE_EXPR3}
code 1
code 2
...
case CASE_EXPR4
code 1
code 2
...
otherwise
code 1
code 2
...
end


For example, we write a script file that converts a value of temperature given in units of either Celcius, Kelvin, or Fahrenheit to the equivalent quantity in different units specified by the user. The program will ask the user to enter the current unit and the new desired unit. The output is the quantity of temperature in the new units. This can be done by using switch by writing a script file as follows:

Unit1 = input('Enter the current units (K,C,F): ','s');
T1 = input('Enter the value of the temperature to be converted: ');
Unit2 = input('Enter the new unit (K,C,F): ','s');

switch Unit1
case 'C'
Tin = T1;
case 'F'
Tin = (T1-32)*(5/9);
case 'K'
Tin = T1-273;
end

switch Unit2
case 'C'
Tout = Tin;
case 'F'
Tout = (5/9)*Tin+32;
case 'K'
Tout = Tin + 273;
end
disp(['The temperature in the new unit is ' num2str(Tout) ' ' Unit2 ]);


First we have used the command input to accept a value from the keyboard. The value can be a numeric or a string. If the value is a string, we put 's' as an option to the input command. The initial unit and the temperature value are kept in Unit1 and T1 respectively. Then we convert T1 to unit of Celcius and assign the value to Tin. Second, we check the new desired unit which is stored in Unit2. The switch will select from the three cases and convert Tin to the new unit and assign the value to Tout. The last command is to display the result on the command window.

## Loops¶

Loops are MATLAB constructs that permit us to execute a sequence of statements more than once. MATLAB has two kind of loops: for and while loops. The major difference between these two types is in how the repetition is controlled. The code in for loop is repeated a specified number of times. The number of repetitions is known before the loop starts. On the other hand, the code in a while loop is repeated an indefinite number of times until some user-specified condition is satisfied.

### The for loop¶

The for loop is a loop that executes a group of codes a specified number of times. It has the form:

for INDEX = EXPR
code 1
code 2
...
end


where INDEX is the loop variable and EXPR is the loop control expression. It usually takes the form of a vector such as first:stepsize:last. It means the loop index (INDEX) will take values from first, first+stepsize, first+2stepsize,..., and last.

• The first time through the loop, the program assigns the first column of EXPR to the variable INDEX, and the program executes the codes inside the body of the loop.
• Next, the program assigns the next column of EXPR to INDEX, and the program executes the codes inside the body of the loop.
• The loop is repeated until INDEX is the last column of EXPR and the program finishes executing the codes. Then the loop is stopped.

A simple example is to assign a value to each entry of a vector:

x = zeros(1,10);
for ii = 1:10
x(ii) = ii^2;
end


In the above example, ii will be 1 on the first time, and x(1) is assigned to the value of 1^2. The ii will be 10 on the last pass and x(10) = 10^2. After then 10th pass, there are no more columns in EXPR (which is the vector 1:10), so the program will skip to the end. The resulting vector x is:

>> x

x =
1     4     9    16    25    36    49    64    81   100


Another example is to show how to find the indices of the entries of a vector x that are nonnegative:

x = randint(1,5,[-3,2]);
jj = 0;
for ii=1:length(x)
if (x(ii) >= 0)
jj = jj+1;
IND(jj) = ii;
end
end


The example is to generate a random vector x that has both nonnegative and negative values. We have to check all entries of x, so the for loop runs for length(x) times. The loop index is ii and the if is used to check if x(ii) is nonnegative or not. If it is, we increase a variable jj by 1. This variable tells us how many number of nonnegative entries of x at the end. The indices of nonnegative entries are kept in IND variable.

An example of the result is:

>> x

x =
1     2    -3     2     0

>> IND

IND =
3     4     5     5


The above example is, in fact, already done as a built-in function called the find command.

Some notes for the usage of the for loop:

• Do not modify the loop index within the body of a loop. The index variable is often used as a counter and modifying its value can cause strange error. For example:

for ii=1:2:10
...
ii = 6;  % ERROR !
...
end

• Be reminded that the use of for loop to allocating arrays is sometimes not efficient and can be avoided by exploiting the element-wise operations instead. For instance, the first example can be done by typing:

ii = 1:10;
x = ii.^2


### The while loop¶

A while loop is a block of statements that are repeated indefinitely as long as some condition is satisfied. The general form is:

while CONDITIONAL_EXPR
code 1
code 2
...
end


The controlling expression produces a logical value (either 1 or 0). If the CONDITIONAL_EXPR is true (1), the code block will be executed, and then the program will return to the while statement. If the CONDITIONAL_EXPR is still true, then the codes will be executed again. This process will be repeated until the CONDITIONAL_EXPR becomes false in which the program will skip to the end to exit the loop.

For example:

x = 1;
while x <= 10
x = 2*x;
fprintf('x = %d \n',x)
end


When executing these codes in the Command Window, it produces:

x = 2
x = 4
x = 8
x = 16


The initial value of x is 1. Then when it passes to the while loop the conditional statement is true (x <= 10 has a logical value of 1), and the program executes the code within the loop body. The value of x is increased by a factor of 2, which is 2 and the program prints out this value to the command window. Next the program goes back to check whether x <= 10 which is still true (2 <= 10 returns 1). The program keeps repeating this way until x == 16 and stops because 16 <= 10 returns false.

Important notes

• The CONDITIONAL_EXPR in the while command must include at least one variable and this variable must have assigned a value before the while is executed for the first time.
• The variable in CONDITIONAL_EXPR must be assigned a new value in the expressions within the loop body. Otherwise, once the loop starts it will never stop since the CONDITIONAL_EXPR remain true.
• If an indefinite loop happens, one can stop the execution by pressing CTRL+C or CTRL+Break keys.

In the following example, we write a script file to compute the Taylor series of which is

However, we will compute an approximate of by using the Taylor series up to n terms. Obviously the larger n is, the lower the error between the approximate and the true value. Given a tolerance value of the error, we will determined n that is required for the approximate to be close to the true value. If n is too large and still does not give the approximate close enough to the true value, we will stop and inform the user that more terms are needed. The following are example of codes that use while loop for this purpose:

x = input('Enter x: ');
n = 1; S = 1; err = exp(x)-S;
while (abs(err) >= 0.01)&(n <= 30)
an = x^n/factorial(n);
S = S+an;
n = n+1;
err = exp(x)-S;
end
if n >= 30
disp('More than 30 terms are needed');
end
fprintf('The approximate of exp(%f) = %f \n',x,S);
fprintf('The number of terms used is: %i \n',n);


## Exercises¶

1. Create a 100-element vector containing the values 1,2,...,100. Then take the square root of all elements whose value is greater than 30 using a for loop and if construct. Also think about another approach that produces the same result using element-wise operation.
2. Write a program to vectorize an m x n array using a for loop. For example, given a matrix

the program should arrange all the entries of A into a vector x where

Compare your result with a built-in function called reshape.

1. Use loops to create an m x n matrix in which the value of each entry is the difference between the indices divided by the sum of its indices. For example, the value of the element (3,2) is (3-2)/(3+2).
2. Write a user-defined function to calculate the geometric mean of a set of n positive numbers , which is defined by

For function name and argument use GM = geomean(x) where x is a vector of numbers (any length) and the output GM is their geometric mean.

1. The factorial of a positive number (integer) is defined by:

where . Write a user-defined function that calculates the factorial of a number. For function name and arguments use y = fact(x), where the input x is the number and the output y is the value of factorial. The function displays a message if a negative or a non-integer number is entered when the function is called. Compare your result with the command factorial.

1. Use MATLAB to plot the function:

in the interval .

1. Construct a square matrix of size n where its diagonals are all 1, superdiagonals and subdiagonals are all 1/2, and the other entries are all zero, i.e.,

This matrix has a Toeplitz structure. Compare your result with the command toeplitz.

1. Given a vector x of any length. Write a function to calculate the number of times that the consecutive entries of x are increasing. For example:

x = [-2     3     3     0     2    -3    -1     3     2     3 ]


Then we read that the first entry is increasing (from -2 to 3), the 4th entry is increasing (from 0 to 2), and so on. There are 5 entries of x that are increasing, so the output of your function returns 5.