This lecture explains some of the most widely used operators, as well as branching statements in MATLAB.

## Lecture Videos

This video is created solely as reference for the attendants of ICP2017F course at UT Austin. If you did not attend this class, then you may not find this video useful.

## MATLAB operators

A complete list of MALTAB operators can be found here. Corresponding to each operator, there is also MATLAB function that does the exact same thing for you.

Symbol | Role | Alternative |
---|---|---|

` + ` | Addition | `plus() ` |

` + ` | Unary plus | `uplus() ` |

` - ` | Subtraction | `minus() ` |

` - ` | Unary minus | `uminus() ` |

` .* ` | Element-wise multiplication | `times() ` |

` * ` | Matrix multiplication | `mtimes() ` |

` ./ ` | Element-wise right division | `rdivide() ` |

` / ` | Matrix right division | `mrdivide() ` |

` .\ ` | Element-wise left division | `ldivide() ` |

` \ ` | Matrix left divison (also known as backslash) | `mldivide() ` |

` .^ ` | Element-wise power | `power() ` |

` ^ ` | Matrix power | `mpower() ` |

` .' ` | Transpose | `transpose() ` |

` ' ` | Complex conjugate transpose | `ctranspose()` |

Symbol | Role | Alternative |
---|---|---|

` == ` | Equal to | `eq()` |

` ~= ` | Not equal to | `ne()` |

` > ` | Greater than | `gt()` |

` >= ` | Greater than or equal to | `ge()` |

` < ` | Less than | `lt()` |

` <= ` | Less than or equal to | `le()` |

Symbol | Role | Alternative |
---|---|---|

` & ` | Logical AND | `and()` |

` | ` | Logical OR | `or()` |

` && ` | Logical AND (with short-circuiting) | -- |

` || ` | Logical OR (with short-circuiting) | -- |

` ~ ` | Logical NOT | `not()` |

### Special characters in MATLAB

There are also a set of characters that have special role in MATLAb, some of which we have already discussed in the past lectures. You can learn about them here.

## Implicit type casting and operator overloading

MATLAB is a loosely or weakly-typed language, which has a number of real-world implications. The first, and probably most notable, difference between MATLAB and a strongly-typed language is that you don’t have to explicitly declare the types of the variables you use. For example, the declarations x=5; x=’foo’ immediately following one another are perfectly acceptable; the first declaration causes x to be treated as a number, the second changes its treatment to a string.

The **main benefit** of using a weakly-typed language is the **ability to do rapid prototyping**. The number of lines of code required to declare and use a dynamically allocated array in C (and properly clean up after its use) are much greater than the number of lines required for the same process in MATLAB. Weak typing is also good for code-reuse. You can code a scalar algorithm in MATLAB and with relatively little effort modify it to work on arrays as well as scalars. The fact that MATLAB is a scripted instead of a compiled language also contributes to rapid prototyping.

Weak typing is not without its pitfalls, though. For example, weak typing combined with unexpected user input can sometimes lead to erroneous results,

```
>> x=5;
>> y=4;
>> x/y
ans =
1.2500
```

whereas the same code in strongly-typed compiled languages, such as C and Fortran would have given *integer* value `1`

.

Weak typing, combined with intrinsic MATLAB **operator overloading** can also can lead to unexpected results when operations between mixed types are done. Consider what happens when you add `1+'1'`

, that is, the scalar 1 and the character ‘1’. The surprising result is 50. MATLAB automatically converts the character `'1'`

to its ASCII representation value, which is 49 (You can get the ASCII code for any character using the `abs()`

function). After this implicit conversion, MATLAB adds the scalar value of `1`

to return `50`

. (Note: While this example is somewhat contrived it can easily arise, especially when passing a function argument where the type is undetermined. To write completely safe weakly-typed code, user input should always be checked before performing operations on it.)

The situation can be more complicated when you deal with strings rather than single characters. For example,

```
>> x=10;
>> y='10';
>> x+y
ans =
59 58
```

Basically, what happened above is that `'10'`

is considered as a vector of characters, therefore, when you add it to `10`

, Matlab automatically converts this string to a vector of corresponding ASCII values and adds the value `10`

to each one.

```
>> 'Hello' + 'World'
ans =
159 212 222 216 211
```

## Explicit type conversion

Unlike implicit type casting which is done by MATLAB under the hood as described above, which can also be dangerous, you can also explicitly request MATLAB to convert the type of a variable to some other type, using MATLAB’s built-in functions like `cast`

, or one of the many other functions that MATLAB has for this purpose.

### Array vs. Matrix Operations

We have already learned that arrays and matrices are not the same in MATLAB. As a result, the operators that can act on them are also not identical.

**Matrix operations** follow the rules of linear algebra and are not compatible with multidimensional arrays. The required size and shape of the inputs in relation to one another depends on the operation. For non-scalar inputs, the matrix operators generally calculate different answers than their array operator counterparts.

**Array operations** execute element by element operations on corresponding elements of vectors, matrices, and multidimensional arrays. If the operands have the same size, then each element in the first operand gets matched up with the element in the same location in the second operand. If the operands have compatible sizes, then each input is implicitly expanded as needed to match the size of the other.

You can learn more about them in MATLAB manual.

### Operator precedence in MATLAB

You can build expressions that use any combination of arithmetic, relational, and logical operators. Precedence levels determine the order in which MATLAB® evaluates an expression. Within each precedence level, operators have equal precedence and are evaluated from left to right. The precedence rules for MATLAB operators are shown in this list, ordered from highest precedence level to lowest precedence level:

- Parentheses
`()`

. - Transpose
`.'`

, power`.^`

, complex conjugate transpose`'`

, matrix power`^`

. - Power with unary minus
`.^-`

, unary plus`.^+`

, or logical negation`.^~`

as well as matrix power with unary minus`^-`

, unary plus`^+`

, or logical negation`^~`

. (Note: Although most operators work from left to right, the operators`^-`

,`.^-`

,`^+`

,`.^+`

,`^~`

, and`.^~`

work from second from the right to left. It is recommended that you use parentheses to explicitly specify the intended precedence of statements containing these operator combinations.) - Unary plus
`+`

, unary minus`-`

, logical negation`~`

. - Multiplication
`.*`

, right division`./`

, left division`.\`

, matrix multiplication`*`

, matrix right division`/`

, matrix left division`\`

. - Addition
`+`

, subtraction`-`

. - Colon operator
`:`

. - Less than
`<`

, less than or equal to`<=`

, greater than`>`

, greater than or equal to`>=`

, equal to`==`

, not equal to`~=`

. - Element-wise AND
`&`

. - Element-wise OR
`|`

. - Short-circuit AND
`&&`

. - Short-circuit OR
`||`

.

You can learn more about operator precedence in MATLAB manual.

## Branching in MATLAB

The normal flow of control in procedural programming paradigm is in general, *sequential*. So is the flow of control in MATLAB.

In MATLAB, you can achieve conditional flow control, using either **if-block** or **switch-case**.

### MATLAB if-blocks

```
a = input('Enter a number:');
if isnumeric(a) && (a >= 0)
root = sqrt(a);
disp(['Square root(',num2str(a),') = ', num2str(root)]);
elseif isnumeric(a) && (a < 0)
disp(['The input number is negative, there is no square root.']);
else
disp(['Please enter a real number!']);
end
```

```
Enter a number:13
Square root = 3.6056
Enter a number:-11
The input number is negative, there is no square root
Enter a number:i
Square root = 0.70711+0.70711i
```

Note in the above example, how MATLAB treats complex variables. More information on operators that can be used to construct or combine logical conditions for if-statements can be found here.

#### Exercise

**1. ** write a MATLAB script that takes two predefined matrices `A`

and `B`

as input and determines whether they have equal size. If so, then it concatenates the two matrices in a column-wise manner.

**answer**

```
if isequal(size(A),size(B))
C = [A; B];
else
disp('A and B are not the same size.')
C = [];
end
```

**2. ** Write a script that checks if it (the script itself) exists!

**answer**

```
if exist('myScript.m','file')
disp('Your file exists! Did you expect otherwise?')
else
disp('Your file does not exist! Then perhaps you don''t exist either??')
end
```

**3. ** Write a script that takes an input predefined number $x$ and calculates the following function,

**answer**

```
x = input('input the value of x: ')
if x >= -1 && x <= 1
y = x
else
y = x^2
end
disp(['y(x=',num2str(x),') = ',num2str(y)])
```

### MATLAB switch-case

Sometimes we may have many if statements which all use conditions based on the same variable. It is not incorrect to use if statements in such cases, but it can lead to a large number of consecutive if statements in our code, making it harder to read and more prone to errors. In this case, it is preferable to use a switch statement. The switch statement offers an easy way of writing code where the same variable needs to be checked against a number of different values.

```
day = input('Enter a day number:');
switch day
case 1
day_name = 'Monday';
case 2
day_name = 'Tuesday';
case 3
day_name = 'Wednesday';
case 4
day_name = 'Thursday';
case 5
day_name = 'Friday';
case 6
day_name = 'Saturday';
case 7
day_name = 'Sunday';
otherwise
day_name = 'Unknown';
end
disp(['The corresponding weekday is ',day_name,'.'])
```

```
Enter a day number:4
The corresponding weekday is Thursday.
```

MATLAB will compare the switch expression (in this case, `day`

) with each case expression in turn (the numbers 1–7). When a comparison evaluates to `true`

, MATLAB executes the corresponding statements and then exits the switch statement, i.e. control flow passes to after the `end`

statement. The `otherwise`

block is optional and executes only when no comparison evaluates to `true`

. Note that the `switch`

statement is used only for equality tests – we cannot use it for other types of comparison (e.g. `>`

, `<`

, etc.).

A `switch`

statement may also take a cell array as one of its cases,

```
day = input('Enter a day number:');
switch day
case {1,2,3,4,5}
day_name = 'Weekday';
case {6,7}
day_name = 'Weekend';
otherwise
day_name = 'Unknown';
end
disp(['The input day number corresponds to ',day_name,'.'])
```

```
Enter a day number:6
The input day number corresponds to Weekend.
```

### Non-boolean conditions in if-statements

There is a rather interesting feature of conditions for if-statements in MATLAB (also in Python language), that allows the programmer to use a non-boolean variable or non-boolean value type directly in place of the condition in if-statement. What really happens here is that, MATLAB interpreter converts the non-boolean type to a boolean value, when it occurs in place of an if-statement condition.

```
if 5.6
disp('The condition in this if statement is automatically converted from float to boolean')
end
```

```
The condition in this if statement is automatically converted from float to boolean
```

```
if ~0.0
disp('A float value of zero is converted to false')
end
```

```
A float value of zero is converted to false
```

```
if 0.0
disp('A float value of zero is converted to false')
end
```

```
if 0.000000000000000000000000000000000000000000000000000000000000000000001
disp('Any non-zero float value of any precision is converted to true')
end
```

```
Any non-zero float value of any precision is converted to true
```

```
if 1.e-323
disp('Any non-zero float value of any precision is converted to true')
end
```

```
Any non-zero float value of any precision is converted to true
```

```
if 1.e-324 % make sure you don't go beyond computer precision
disp('Any non-zero float value smaller than the computer precision will be set to 0')
end
```

```
if ~1.e-324 % make sure you don't go beyond computer precision
disp('Any non-zero float value smaller than the computer precision will be set to 0')
end
```

```
Any non-zero float value smaller than the computer precision will be set to 0
```

```
if 12
disp('The same rules also hold for integers.')
end
```

```
The same rules also hold for integers.
```

```
if ''
disp('An empty string is always converted to boolean false, because it is considered an empty logical vector.')
end
```

```
if ''
else
disp('An empty string is always converted to boolean false, because it is considered an empty logical vector.')
end
```

```
An empty string is always converted to boolean false, because it is considered an empty logical vector.
```

```
if []
else
disp('An empty vector is always converted to boolean false, because it is considered an empty logical vector.')
end
```

```
An empty vector is always converted to boolean false, because it is considered an empty logical vector.
```

But note that conversion from cell to logical is not possible in MATLAB:

```
if {}
disp('An empty cell cannot be converted to boolean value, because MATLAB wants it that way!')
end
```

```
Conversion to logical from cell is not possible.
```

```
if ['amir']
disp('A non-empty vector is converted to boolean true.')
end
```

```
A non-empty vector is converted to boolean true.
```

```
if ' '
disp('A non-empty string is converted to boolean true.')
end
```

```
A non-empty string is converted to boolean true.
```

### MATLAB’s built-in **is** functions

MATLAB has a wide range of functions whose names begins with `is`

, and their output is a logical value type, which can be used in if-blocks. These functions are extremely useful in MATLAB coding, and you will encounter them frequently in your computational life. Here is a rather comprehensive list of them,

Expression | Description |
---|---|

`isa()` | Detect object of given MATLAB class or Java® class |

`isappdata()` | Determine if object has specific application-defined data |

`isbetween()` | Array elements occurring within date and time interval |

`iscalendarduration()` | Determine if input is duration array |

`iscategorical()` | Determine whether input is categorical array |

`iscategory()` | Test for categorical array categories |

`iscell()` | Determine if input is cell array |

`iscellstr()` | Determine if input is cell array of strings |

`ischar()` | Determine if input is character array |

`iscolumn()` | Determine whether input is column vector |

`iscom()` | Determine if input is Component Object Model (COM) object |

`isdatetime()` | Determine if input is datetime array |

`isdir()` | Determine if input is folder |

`isdst()` | Datetime values occurring during daylight saving time |

`isduration()` | Determine if input is duration array |

`isempty()` | Determine if input is empty array |

`isequal()` | Determine if arrays are numerically equal |

`isequaln()` | Determine if arrays are numerically equal, treating NaNs as equal |

`isevent()` | Determine if input is Component Object Model (COM) object event |

`isfield()` | Determine if input is MATLAB structure array field |

`isfinite()` | Detect finite elements of array |

`isfloat()` | Determine if input is floating-point array |

`ishandle()` | Detect valid graphics object handles |

`ishold()` | Determine if graphics hold state is on |

`isinf()` | Detect infinite elements of array |

`isinteger()` | Determine if input is integer array |

`isinterface()` | Determine if input is Component Object Model (COM) interface |

`isjava()` | Determine if input is Java object |

`iskeyword()` | Determine if input is MATLAB keyword |

`isletter()` | Detect elements that are alphabetic letters |

`islogical()` | Determine if input is logical array |

`ismac()` | Determine if running MATLAB for Macintosh OS X platform |

`ismatrix()` | Determine whether input is matrix |

`ismember()` | Detect members of specific set |

`ismethod()` | Determine if input is object method |

`ismissing()` | Find table elements with missing values |

`isnan()` | Detect elements of array that are not a number (NaN) |

`isnumeric()` | Determine if input is numeric array |

`isobject()` | Determine if input is MATLAB object |

`isordinal()` | Determine whether input is ordinal categorical array |

`ispc()` | Determine if running MATLAB for PC (Windows®) platform |

`isprime()` | Detect prime elements of array |

`isprop()` | Determine if input is object property |

`isprotected()` | Determine whether categories of categorical array are protected |

`isreal()` | Determine if all array elements are real numbers |

`isrow()` | Determine whether input is row vector |

`isscalar()` | Determine if input is scalar |

`issorted()` | Determine if set elements are in sorted order |

`isspace()` | Detect space characters in array |

`issparse()` | Determine if input is sparse array |

`isstrprop()` | Determine if string is of specified category |

`isstruct()` | Determine if input is MATLAB structure array |

`isstudent()` | Determine if Student Version of MATLAB |

`istable()` | Determine whether input is table |

`isundefined()` | Find undefined elements in categorical array |

`isunix()` | Determine if running MATLAB for UNIX®[a] platform. |

`isvarname()` | Determine if input is valid variable name |

`isvector()` | Determine if input is vector |

`isweekend()` | Datetime values occurring during weekend |

For more information on each individual function, see MATLAB’s use manual.