This lecture further explains values and variables in MATLAB, as well as common MATLAB operators.

For general information on MATLAB Data Types, see MATLAB manual.

## 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.

## Variables in MATLAB

A variable is simply a name that we assign to a specific value, in order to avoid repeating the same value frequently in the code, thus writing a cleaner, less error-prone script/code. We discussed in previous lecture, the main values types (classes) in MATLAB. The same also holds for variables, because they are simply names assigned to each value or a set of values. In order to define a variable, the varable name must always appear on the left of an equality, like the following,

```
>> format compact
>> a = 1 % assign value 1 to a
a =
1
>> class(a)
ans =
double
>> 1 = b % this is wrong
1 = b
↑
Error: The expression to the left of the equals sign is not a valid target for an assignment.
```

We will get to each of these below. But before that, here are some official and unofficial tips on the variable naming conventions in MATLAB.

### Variable naming convention in MATLAB

A MATLAB variable can only begin with letter followed by underscore `_`

and numbers inside or at the end of the variable name. MATLAB is case sensitive, so `A`

and `a`

are not the same variable. Other symbols are syntactically invalid anywhere in a variable name. Examples of valid names:

`x6`

`lastValue`

`n_factorial`

Invalid names:

`6x`

`n!`

`end`

(see below for the reason)

```
>> new_var$
new_var$
↑
Error: The input character is not valid in MATLAB statements or expressions.
```

```
>> amir = 'teacher';
disp(['Amir is a', amir])
Amir is ateacher
```

```
>> life_expectancy = 120; disp( ['The life expectancy for the millennials is projected to be ',life_expectancy,' years! (But don''t believe it...)'] )
The life expectancy for the millennials is projected to be x years! (But don't believe it...)
```

#### MATLAB reserved names (keywords)

There are some limitation as to what names you can choose for your variables, even if they completely obey MATLAB syntax standard. Variable names in MATLAB cannot be the same as **MATLAB keywords**, which are simply names that reserved for a specific purpose in MATLAB programming. They are used to define the syntax and structure of the MATLAB language. Note that **MATLAB keywords are case-sensitive**. You **cannot** define variables with the exact same names as **MATLAB keywords**, such as `if`

or `end`

. For a complete list of MATLAB keyword, run the `iskeyword`

command,

```
>> iskeyword
ans =
'break'
'case'
'catch'
'classdef'
'continue'
'else'
'elseif'
'end'
'for'
'function'
'global'
'if'
'otherwise'
'parfor'
'persistent'
'return'
'spmd'
'switch'
'try'
'while'
```

#### Predefined variables in MATLAB

Note that there are some predefined variables in MATLAB, that are not considered as keywords. Therefore you can change their values and use them for your own purposes. But, **be very careful with predefined variables and in general**, it is better to not mess with them, as they can lead to confusion and catastrophe. For example,

```
>> true % true is a predefined MATLAB logical variable
ans =
1
>> class(true)
ans =
logical
>> true = 0 % but I have redefined it as double
true =
0
>> class(true)
>> nan
ans =
NaN
>> class(nan)
ans =
double
>> nan = true
nan =
0
>> nan = false % redefine nan
nan =
0
>> class(nan)
ans =
logical
```

```
>> who
Your variables are:
life_expectancy nan true
>> whos
Name Size Bytes Class Attributes
life_expectancy 1x1 8 double
nan 1x1 1 logical
true 1x1 8 double
>> clear nan
>> who
Your variables are:
life_expectancy true
>> clear all
>> whos
>> who
>> pi
ans =
3.1416
>> nan
ans =
NaN
>> inf
ans =
Inf
>> i
ans =
0.0000 + 1.0000i
>> j
ans =
0.0000 + 1.0000i
```

Here is a list of som eof the most important predefined variables in MATLAB.

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

`pi ` | The number $\pi$ up to 15 significant digits. |

`i, j ` | The complex number $\sqrt{-1}$. |

`inf ` | Represents the mathematical Infinity concept, for example, a result of division by zero. |

`NaN ` | Stands for Not-A-Number. Represents the result of a meaningless mathematical function, like $0/0$. |

`clock` | Contains the current date and time in the form of a 6-element row vector: year,month,day,hour,minute,second. |

`date ` | Contains a string representing today's date. |

`eps ` | Stands for epsilon. It represents the smallest number that can be represented by your MATLAB software. |

`ans ` | A special variable that MATLAB uses to store the result of MATLAB's command line. |

### Numeric variables

We have already extensively discussed number values in the previous lecture. Basically, everything that we have said about number values, holds also for variables of type number.

### Vector and matrix variables

Again, similar to vector and matrix values, everything holds for the same type variables.

```
>> a = [1,2,3,4]
a =
1 2 3 4
>> class(a)
ans =
double
>> a = [1;2;3;4]
a =
1
2
3
4
```

#### The colon operator `:`

MATLAB has a special character shortcut notation for occasions when you want to create a numeric vector of a specific range with predefined fixed spacing between the values of the vector. This shortcut has the following form,

```
begin:increment:end
```

For example,

```
>> x = 0:10:100
x =
0 10 20 30 40 50 60 70 80 90 100
```

#### The transpose operator `'`

Now as you may have noticed, MATLAB by default creates row-wise vectors, just as `x`

was generated above. If you want to initialize `x`

as a column-wise vector, all you need to do is to add the transpose operator `'`

at the end of the vector or the variable name (but now, you would also need the vector constructor `[]`

),

```
>> x = [0:10:100]'
x =
0
10
20
30
40
50
60
70
80
90
100
>> whos x
Name Size Bytes Class Attributes
x 11x1 88 double
```

Now, pay attention to the size of the vector `x`

. What does it mean when it says `88 Bytes`

?

#### Creating matrices

There are a number of functions in MATLAB that can help you build predefined matrices or vectors.

##### zeros

Creates array of all zeros (with optionally given fixed-point properties. For more information, see MATLAB’s manual.

```
>> zeros(2,2)
ans =
0 0
0 0
```

```
>> a = zeros(1,3)
a =
0 0 0
```

##### ones

Creates array of all ones with fixed-point properties.

```
>> a = ones(1,3)
a =
1 1 1
```

##### eye

Creates identity matrix with fixed-point properties

```
>> I = eye(3,3)
I =
1 0 0
0 1 0
0 0 1
>> I = eye(3,4)
I =
1 0 0 0
0 1 0 0
0 0 1 0
```

##### diag

Creates a diagonal matrix from a given input vector,

```
v = [2 1 -1 -2 -5];
>> D = diag(v)
D =
2 0 0 0 0
0 1 0 0 0
0 0 -1 0 0
0 0 0 -2 0
0 0 0 0 -5
>> D = diag(v,2)
D =
0 0 2 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 -1 0 0
0 0 0 0 0 -2 0
0 0 0 0 0 0 -5
0 0 0 0 0 0 0
0 0 0 0 0 0 0
>> D = diag(v,-2)
D =
0 0 0 0 0 0 0
0 0 0 0 0 0 0
2 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 -1 0 0 0 0
0 0 0 -2 0 0 0
0 0 0 0 -5 0 0
```

`diag`

can also get diagonal elements of an input matrix, if it already exists.

```
>> a = eye(3,5)
a =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
>> diag(a)
ans =
1
1
1
>> diag(a,-1)
ans =
0
0
>> diag(a,1)
ans =
0
0
0
```

##### ndgrid

Creates rectangular grid in N-D space.

```
>> [X,Y] = ndgrid(1:2:19,2:2:12)
X =
1 1 1 1 1 1
3 3 3 3 3 3
5 5 5 5 5 5
7 7 7 7 7 7
9 9 9 9 9 9
11 11 11 11 11 11
13 13 13 13 13 13
15 15 15 15 15 15
17 17 17 17 17 17
19 19 19 19 19 19
Y =
2 4 6 8 10 12
2 4 6 8 10 12
2 4 6 8 10 12
2 4 6 8 10 12
2 4 6 8 10 12
2 4 6 8 10 12
2 4 6 8 10 12
2 4 6 8 10 12
2 4 6 8 10 12
2 4 6 8 10 12
```

Later on, we will see how this function can be used to generate fancy looking graphs like the following,

#### Matrix concatenation functions

The following functions combine existing matrices to form a new matrix.

**cat**: Concatenate matrices along the specified dimension**horzcat**: Horizontally concatenate matrices**vertcat**: Vertically concatenate matrices**repmat**: Create a new matrix by replicating and tiling existing matrices**blkdiag**: Create a block diagonal matrix from existing matrices

### Cell variables

When we want to define a variable whose elements are not all of the same type, we need an entity that goes beyond the capabilities of matrices, which can only contain numeric values. Just as with cell values in the previous lecture, a cell array is a data type with indexed data containers called cells. Each cell can contain any type of data. Cell arrays commonly contain **pieces of text (string)**, **combinations of text and numbers** from spreadsheets or text files, or they can contain arrays of numeric arrays of different sizes.

There are two ways to refer to the elements of a cell array. Enclose indices in smooth parentheses, (), to refer to sets of cells — for example, to define a subset of the array. Enclose indices in curly braces, {}, to refer to the text, numbers, or other data within individual cells.

#### Creating cell arrays

```
>> C = {} % empty cell array
C =
{}
>> class(C)
ans =
cell
>> size(C)
ans =
0 0
>> length(C)
ans =
0
```

```
>> emptyCell = cell(3,4)
emptyCell =
[] [] [] []
[] [] [] []
[] [] [] []
>> emptyCell = cell(3,4,2)
emptyCell(:,:,1) =
[] [] [] []
[] [] [] []
[] [] [] []
emptyCell(:,:,2) =
[] [] [] []
[] [] [] []
[] [] [] []
```

```
>> a = {'Hi', ' ', 'World!'} % a cell array of strings
a =
'Hi' ' ' 'World!'
>> class(a)
ans =
cell
>> size(a) % the length of a, in all directions (dimension)
ans =
1 3
>> length(a) % the length of a, along the longest dimension
ans =
3
```

To call a specific element, use `()`

.

```
>> names = {'Bloggs', 'San', 'Andersen'};
>> first_cell = names(1);
>> rest_of_cells = names(2:3);
>> third_string = names{3};
```

You can see what the type of each element is by using `who`

and `whos`

,

```
>> whos
Name Size Bytes Class Attributes
a 1x3 354 cell
ans 1x1 8 double
chr 1x12 24 char
first_cell 1x1 124 cell
names 1x3 370 cell
rest_of_cells 1x2 246 cell
third_string 1x8 16 char
```

Note that `who`

only gives you the names of the variables,

```
>> who
Your variables are:
a ans chr first_cell names rest_of_cells third_string
```

#### Cell array concatenation functions

There are a wide range of MATLAB functions that act on cells, which can be found here.

### String (char) variables

Just as explained in the last lecture,

```
>> newChr = 'You''re right'
newChr =
You're right
>> class(newChr)
ans =
char
```

#### Creating string arrays

Creating string arrays is rather complex and confusing in MATLAB. Here is MATLAB’s own manual for creating string arrays. Note that a string is a vector by itself. So you can fetch its characters as elements,

```
>> newChr = 'You''re right'
newChr =
You're right
>> newChr(1)
ans =
Y
>> newChr(1:4)
ans =
You'
```

### Structure variables

Let’s first review the meanings of Arrays and Cells:

- An
**array**is a MATLAB data type in which there is a name for the whole data object, and the individual elements in the array can be accessed only through their indices, which are integer numbers. For example,`>> arr = [1,2,3,4] arr = 1 2 3 4`

But, notice that**all the elements in a MATLAB array must be of the same data type**. For example, you cannot combine numeric and string data types,`>> arr = [1,'Amir',3,4] arr = Amir`

- By contrast, a
**cell array**is a MATLAB data type in which again, there is a name for the whole data object, and the individual elements in the array can be accessed only via their indices, but unlike regular arrays**cell elements do not need to be all of the same type**,`>> arr = {1,'Amir',3,4} arr = [1] 'Amir' [3] [4]`

- There is yet another data type in MATLAB called
**structure**, which has also counterparts in most other programming lansuages such as Fortra, C, C++. This is the topic of this section below.

A **structure** is MATLAB data type in which the whole object has a name, just like regular and cell arrays. However, unlike cells and regular arrays, the elements of a structure object can be accessed by their assigned **field names** instead of a numarical index, as in numeric arrays and cells.

Like cell arrays, structures can contain data of varying types and sizes. A structure object is a MATLAB data type that groups related data using data containers called **fields** (instead of cells as in cell arrays). **Each field can contain any type of data**. You can access data in a structure using **dot notation** of the form `structName.fieldName`

. Here is MATLAB video about cell and structure arrays.

#### Creating structures

To create a structure, you can use function `struct`

,

```
>> field = 'f';
value = {'some text';
[10, 20, 30];
magic(5)};
s = struct(field,value)
s =
3x1 struct array with fields:
f
```

You can also create empty structure (which can be manipulated later),

```
>> s = struct()
s =
struct with no fields.
```

One can also create structure objects by simply using the dot notation,

```
>> amir.univ = 'UT Austin'
amir =
univ: 'UT Austin'
```

Structure objects described above are examples of **scalar objects** meaning that there is only one single structure object with a set of fields. However, MATLAB also provides ways of creating **structure arrays**. You might think of structure array, as a cell array, whose columns are indexed by character names (field names) instead of integer indices, and whose rows represent the elements of the structure array. For example,

```
>> student.name = 'Marshall'
student =
name: 'Marshall'
>> student.grade = 4.0
student =
name: 'Marshall'
grade: 4
>> student
student =
name: 'Marshall'
grade: 4
```

would create a scalar structure `student`

with two fields. However, as soon as you add another name to this structure, using array notation like the following,

```
>> student(2).name = 'vivek'
student =
1x2 struct array with fields:
name
grade
```

the scalar structure `student`

is automatically converted to a **structure array**, that has two rows indexed by integer numbers, and each row has two fields `name`

and `grade`

. Note that, even though we added only the `name`

field for the second structure element, the other field name is also automatically created for the second structure element, although with no content (the content of the field `grade`

for the second structure element is empty). There is even no need to add the elements in increasing order. For example,

```
>> student(4).name = 'travis'
student =
1x4 struct array with fields:
name
grade
>> whos student
Name Size Bytes Class Attributes
student 1x4 654 struct
```

will automatically add (initialize) the third structure element, even though we did not ask for it.

So, if there is so much similarity between MATLAB **cell arrays** and **structure arrays**, then what the advantage of defining or using structure arrays instead of cell arrays? The main advantage is that, in the case of structures, the content of the structure element is identified by set of tags (labels) called **field names**. This becomes very helpful in understanding the content of complex data, when they are written as structures instead of cell arrays.

There is a along list of functions that can manipulate structures. A list of them is available on MATLAB website here.

### MATLAB tables

Tables are arrays in tabular form whose named columns can have different types. A table is a data type suitable for column-oriented or tabular data that is often stored as columns in a text file or in a spreadsheet. Tables consist of rows and column-oriented variables. Each variable in a table can have a different data type and a different size **with the one restriction** that **each variable must have the same number of rows**. For more information, see MATLAB’s educational video on Tables.

To create a table, you can use the function `table`

:

```
>> LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
>> Age = [38;43;38;40;49];
>> Height = [71;69;64;67;64];
>> Weight = [176;163;131;133;119];
>> BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
>> T = table(Age,Height,Weight,BloodPressure,'RowNames',LastName)
T =
Age Height Weight BloodPressure
___ ______ ______ _____________
Smith 38 71 176 124 93
Johnson 43 69 163 109 77
Williams 38 64 131 125 83
Jones 40 67 133 117 75
Brown 49 64 119 122 80
```

There is also a long list of functions that act on tables, a summary of which is available here.

## The Different Kinds of Brackets: Recap

To recap, perhaps the two most two basic operations relating to arrays are,

- Creating the array.
- Accessing elements in the array.

Depending on whether we have a cell array or a standard array of a basic data type (e.g. char), we can distinguish the different behavior of each of the types of brackets: `[]`

, `{}`

and `()`

.

### Creating an Array

**Square brackets**: Creates an array where all entries have the same type, e.g. double or char. For example,`[ ]`

`numArray = [5, 62.7, 3]; charArray = ['a', 'b', 'c'];`

**Curly brackets**: Creates a cell array. Its cells can contain any type. They can contain items of the same type or a mixture of types. For example,`{ }`

`sameTypeCells = {'Once', 'upon', 'a', 'time'} diffTypeCells = {'Number', 17}`

Note that in order to create a vector, you don’t necessarily need ‘,’ between the elements. For example,

```
>> [1 4]
ans =
1 4
>> whos ans
Name Size Bytes Class Attributes
ans 1x2 16 double
>> [1,4]
ans =
1 4
>> whos ans
Name Size Bytes Class Attributes
ans 1x2 16 double
```

The same is also true for cell arrays,

```
>> sameTypeCells = {'Once' 'upon' 'a' 'time'}
sameTypeCells =
'Once' 'upon' 'a' 'time'
>> whos sameTypeCells
Name Size Bytes Class Attributes
sameTypeCells 1x4 474 cell
```

### Accessing Elements

**Round brackets**: These can be used to access one or more elements from any type of array. The elements returned always have the same type as the array, i.e. for an array of doubles the round bracket will return doubles, for an array of cells they will return cells. For example, using the arrays created above:`( )`

`>> numArray(2:3) % Second and third elements. ans = 62.7000 3.0000`

`>> y = sameTypeCells([1, 3]) % first and third y = 'Once' 'a'`

**Curly brackets**: When used for accessing elements, curly brackets are specific to cell arrays. They can be used to obtain the content of a cell in its native data type, i.e. not in the form of a cell. For example,`{ }`

`>> sameTypeCells{2} ans = upon >> class(sameTypeCells{2}) ans = char >> sameTypeCells(2) ans = 'upon' >> class(sameTypeCells(2)) ans = cell`

### Array slicing (indexing)

Like Fortran and R, MATLAB has powerful built-in array manipulation capabilities. For example,

```
>> test = [ 1,2,3,4 ; 1,2,4,5 ; 3,5,6,7 ]
test =
1 2 3 4
1 2 4 5
3 5 6 7
>> test(:,:)
ans =
1 2 3 4
1 2 4 5
3 5 6 7
```

The symbol `:`

means all the elements. But, you could also specify a range to only get a slice of the array,

```
>> test(1:2,2:3)
ans =
2 3
2 4
```

Now, suppose you only wanted to get the first and the last column of the array, and the rows two and three. You could do,

```
>> test(2:3,[1 4])
ans =
1 5
3 7
```

Amazing, isn’t it? You can also slice cell arrays in a similar way. However, note that you can only slice the elements of a cell array in this way, **not the contents of the elements of a cell array**. To explain this further, consider the following cell array,

```
>> test = { 1,2,3,4 ; 1,2,4,5 ; 3,5,6,7 }
test =
[1] [2] [3] [4]
[1] [2] [4] [5]
[3] [5] [6] [7]
```

Now, note that slicing this cell, would give you a cell slice, not a matrix of the values, and note that to do this, you have to access the elements using `()`

instead of `{}`

.

```
>> test(:,:)
ans =
[1] [2] [3] [4]
[1] [2] [4] [5]
[3] [5] [6] [7]
>> test(2:3,[1 4])
ans =
[1] [5]
[3] [7]
>> class(test(2:3,[1 4]))
ans =
cell
```

If you try slicing the cell array using `{}`

, you won’t get a slice anymore, but a MATLAB comma-separated list,

```
>> test{2:3,[1 4]}
ans =
1
ans =
3
ans =
5
ans =
7
>> class(test{2:3,[1 4]})
Error using class
The CLASS function must be called from a class constructor.
```

Since slicing the cell array by `{}`

returns a comma-separated list, MATLAB’s `class()`

function gives an error, since it cannot take as input, a list of values.