# CS425 Lab: Introduction to MATLAB

## 1. MATLAB

### 1.1 What is MATLAB?

• Is a high-performance language
• Stands for Matrix Laboratory
• Can be used as a fancy calculator
• Allows you to easily work with entire matrices rather than one number at a time
• Is useful for anything that requires matrix and vector manipulations such as:
• Mathematical, scientific, engineering, statistical and financial problems
• Anything that requires plotting/visualizing and analyzing data
• Comes with a basic set of tools for visualizing data and for performing calculations on matrices and vectors
• For specific technologies, MATLAB provides toolboxes, which add to the basic MATLAB functionality. We have the Image Processing Toolbox. Some other toolboxes include:
• Statistics Toolbox
• Neural Network Toolbox
• Fuzzy Logic Toolbox
• Signal Processing Toolbox
• Wavelet Toolbox
• Financial Toolbox
• Bioinformatics Toolbox
• Database Toolbox

### 1.2 Matlab screen

The Matlab screen mainly include 4 parts:Command Window, Workspace window,Command History window and Current Directory window.

Command Window – this is where you type commands and usually theoutputs (or error messages) appear here too

Workspace window – if you define new variables there names should be listed here.

Command History window – this is where past commands are remembered. If you want to re-run a previous command or to edit it you can drag it from this window to the command window or double click to re-run it.

Current Directory window- show the files in Current Directory.

## 2 basic operation

### 2.1 Creating a Matrix

Everything in MATLAB is stored as a matrix or an array. To create, a 1x1 array, you can write:

`a=5 `

To see that `a` is a 1x1 array, you can execute the command:

`whos`

`who` lists all of the variables, and `whos` lists the variables and the size.

To create a 4 x 4 matrix, you can use the following syntax.

`b=[1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]`

or

``` b=[1  2  3  4
5  6  7  8
9 10 11 12
13 14 15 16
]```
• opening and closing square brackets are required in this case
• a semicolon (;) is needed in the first example to indicate the end of the row
• if you follow either of the above statements with a semicolon (;), you will notice that it does not echo the matrix to the display
• if you want to remind yourself of what is in `b`, you can type `b` and enter

You can also use MATLAB functions to generate matrices. The following table summarizes a few of these functions:

function description
`zeros(i,j)` creates an `i x j` matrix of zeros
`ones(i,j)` creates an `i x j` matrix of ones
`rand(i,j)` creates an `i x j` matrix of random elements (between 0 and 1)
`randn(i,j)` creates an `i x j` matrix of random elements drawn from a normal distribution with mean 0 and standard deviation 1

In the above table, `i` is the number of rows and `j` is the number of columns. Be careful, this may confuse you if you are used to thinking in terms of x and y.

If you have a large amount of data, you may want to store your data in a file and load it into MATLAB. When you are typing the contents of the file, each column value is separated by white space and each row is on a new line. You require the same number of elements in each row. For instance, you can create a text file (called `myData.dat`) with the following contents:

```   5.0   3.2   6.8
1.4  12.6   3.9
7.1  16.4   8.3
9.3   5.2   4.7```

To read in the file and store it in a variable called `myData`, you use the following command:

`load myData.dat`

### 2.2 Basic Matrix operations

Given b (below), the following table summarizes a few basic matrix operations and the results of these functions:

```b =
1   2   3   4
5   6   7   8
9  10  11  12
13  14  15  16```
Function Description Results
`sum(b)` Sums the values of each column*
```ans =
28    32    36    40```
`diag(b)` Produces all of the elements along the diagonal
```ans =
1
6
11
16```
`b' ` Transpose operator. The first column becomes the first row, the second column becomes the second row and so on
```ans =
1     5     9    13
2     6    10    14
3     7    11    15
4     8    12    16```
`max(b)` Produces the maximum values for each column*
```ans =
13    14    15    16```
`min(b)` Produces the minimum values for each column*
```ans =
1     2     3     4```
`mean(b)` Produces the average of each column
```ans =
7     8     9    10```
`mean2(b)` Produces the average of all the numbers in the matrix
```ans =
8.5000```

*It is great to know the maximum values or sums of each column, but sometimes you want for the entire matrix. If you have a multidimensional matrix, you can turn it into a single column matrix using the notation b(:) (discussed in the "Colon Operator" section below). For instance, to get the sum of all the values in b, you can write:

`sum(b(:))`

```ans =
136```

### 2.3 Subscripts

Given `b` (from above), if you want to access the element in the first row and the forth column, you can use the notation

`b(1,4)`

The results are the following:

```ans =
4```

Notice two things:

• you don't start at index 0
• and the order is in `row,column` format.

You can also use a single index. In this case, MATLAB regards your matrix as one long column that is the concatenation of each of the original columns. For instance, to access the same element as above using a single index, you would write: `b(13)`

MATLAB provides error checking so that you do not exceed the bounds of the matrix. For instance, typing: `b(1,5)` results in:

`??? Index exceeds matrix dimensions.`

However, if you want to add to an existing matrix, you can use an assignment statement such as `b(1,5)=17`, which creates the following matrix:

```b =

1     2     3     4    17
5     6     7     8     0
9    10    11    12     0
13    14    15    16     0```

In this case, a new (fifth) column has been created and it has been padded with zeros where no values were specified.

### 2.4 Colon Operator

The colon operator(:) can be used to select ranges or blocks of values.

By typing `b` and hitting return, you will see the values in `b`:

```b =
1     2     3     4
5     6     7     8
9    10    11    12
13    14    15    16
```

If you only want a subset of b, for instance, the inner square, you can type: `b(2:3,2:3)`

```ans =
6     7
10    11
```

Let's break down the `b(2:3,2:3)` a little. MATLAB is accessing row two to three (2:3) inclusive and column two to three (2:3) inclusive. Other than that, we are looking at the same `(row,column)` notation that you are used to.

Outside of the subscript notation, the colon operator will create a row vector containing the integers in the range specified. For instance, typing `2:8` results in:

```ans =
2     3     4     5     6     7     8```

You can also specify an increment or decrement (as a middle argument) with the colon operator. For instance, typing `1:2:8` results in:

```ans =
1     3     5     7```

In this case, the increment is 2. Effectively, you are getting all of the odd numbers between 1 and 8.

Just to give you more examples, the following table summarizes the results of using the colon operator both as a subscript to `b` and on its own:

Expression Result Description
`5:10`
```ans =
5     6     7     8     9    10```
Values 5 to 10.
`10:-1:5`
```ans =
10     9     8     7     6     5```
Values 10 to 5 (using decrement of 1)
`b(1:2,3:4)`
```ans =
3     4
7     8```
Row 1 to 2, Column 3 to 4 (gets the postage stamp values in the upper right hand corner of b)
`b(5:8)`
```ans =
2     6    10    14```
This is using the single index notation. Remember it is a concatenation of one column after the other. In this case, you are getting the values of the second column.
`b(end)`
```ans =
16```
`end` is a special value which indicates the end of the matrix. This is single index notation. You could have also written `b(end,end)` to specify the ending row and the ending column.
`b(1:4,4)`
``` ans =
4
8
12
16```

This gets the values of the last column (rows 1 to 4 and column 4). Since you are specify all rows and the final column, you could also use the notation:
`b(1:end,end)`
or the colon operator on its own, which specifies the entire range of rows
`b(:,end)`

`b(end:-1:1,:)`
```ans =
13      14    15    16
9      10    11    12
5       6     7     8
1       2     3     4```
Reverses the order of the rows so that the last row is first and the first row is last. Rows last to first with a decrement of 1 (end:-1:1) and all columns(:)
`b(:)`
```ans =
1
5
9
13
2
6
10
14
3
7
11
15
4
8
12
16```
Produces one long column, which is a concatenation of the individual columns. This is useful when using functions such as `max`, `min`, or `sum`

### 2.5 Variables

• When you are declaring a variable, you do not need to specify the type or the dimensions (think about how this compares to creating an array in C++)
• If there is another assignment statement using the same variable name, then MATLAB will change the contents and, where necessary, allocate new storage.
• Variable names are case sensitive (`b` and `B` are two separate variables).
• Variable names are a letter followed by any number of letters, digits, or underscores. Notice that there are no special characters allowed, for instance, the dollar sign (\$) is not valid in variable names as it is in some other languages
• Variable names can be any length, but only the first `N` characters of the variable will be used. To see what `N` is, you can type:
`namelengthmax`
• Every variable declared is an array/matrix. For instance, `myVar=2` creates a 1x1 matrix with a single element (`2`).

### 2.6 Predefined Functions and Help

The basic MATLAB package provides you with a number of functions that are useful for working with numbers and arrays. All of the following functions are part of the MATLAB base: `sin`, `cos`, `sqrt`, `abs`, `ceil`, `isprime`, `gcd`, `lcm`, `find`, `rot90`, `size`, `length`, `isempty`, and `isequal`.

For a more extensive list of some of the functions available to the basic MATLAB package, you can type the following commands:

 `help elfun` (for more on elementary mathematical functions) `help specfun` (for more on specialized mathematical functions) `help elmat` (for more on elementary matrices and matrix manipulations)

For a list of the functions available to MATLAB's Image Processing Toolbox, you can type the following command:

 `help images ` (for more on Image Processing Toolbox)

If you want more help on a specific function, you can type:

`help functionName`

For instance, if you want to know more about the `sin` function. You can type:

`help sin `

or better yet:

`doc sin `

which opens up an indexed help window with further details about `sin`.

`sin` is a built-in function, which means that it is part of the MATLAB core and you cannot see the code behind this function. By contrast, there are functions such as `acosd` that are implemented in M-files. The file (`acosd.m`) is stored in: `matlabroot\toolbox\matlab\elfun` (where `matlabroot` is the installation directory of MATLAB). You can view this file directly from MATLAB using:

`type acosd.m ` (typing .m, in this case, is optional)

or to edit, you can type:

`edit acosd`

### 2.7 The M-Files

The edit command in the above section shows you a very basic M-File for the `acosd` function. The following is meant to summarize M-Files:

• M-Files are text files with MATLAB code
• M-Files have a .m extension
• To create a basic M-File that works as a script to create an array called `A`:
• Use Notepad or some other editor to type the following:
```A=[
1 2
3 4 ];     ```
• Notice that there is a semicolon at the end of this statement. Remember, this suppresses output.
• Save the file as `Mym.m`
• Make sure that all your resource files are saved in the "Current Directory", You should see `Mym.m` as in the diagram below. Otherwise, Matlab can't search to find them when running.
• run the file by typing:
`Mym`
• Voila, `A` should now be created.

### 2.8 Concatenation

The concatenation operator is indicated with square brackets []. Without even knowing it, you have been concatenating simple 1x1 arrays into multidimensional arrays with statements like the following that creates a 2x2 array called `A`:

` A=[1  2 ; 3  4]`

To create an 4x4 array, which repeats the elements of `A` three times, you can write:

`[A A; A A]`

that results in:

```ans =
1     2     1     2
3     4     3     4
1     2     1     2
3     4     3     4
```

You can also have two occurances of `A` (one below the other) and at the same time reverse the second occurance of `A` as in:

`[A;A(end:-1:1,:)]`

that results in:

```ans =
1     2
3     4
3     4
1     2 ```

### 2.9 Modifying Values or Deleting Rows

Let's say you have created `b` as below:

```b =
1     2     3     4
5     6     7     8
9    10    11    12
13    14    15    16```

If you want to change an element, you can do so using subscripts and assignment as in:

`b(3,1)=3`

which results in:

```b =
1     2     3     4
5     6     7     8
3    10    11    12
13    14    15    16```

You can also change an entire row by specifying:

`b(3,:)=3`

which results in:

```b =
1     2     3     4
5     6     7     8
3     3     3     3
13    14    15    16```

If you decide to delete anything, you can use `[]` (empty square brackets). For instance, to delete the fourth row of `b`, you can write:

`b(4,:)=[]`

which results in:

```b =
1     2     3     4
5     6     7     8
3     3     3     3```

However, you cannot partially remove a row and column. For instance, the following produces an error:

`b(1:2,2)=[]`

You could, however, remove every fourth element and collapse the remaining elements into a row matrix as in:

`b(1:4:end)=[]`

which results in:

```b =
5     3     2     3     3     7     4     8     3```

### 2.10 Matrix Operations Versus Array Operations

In MATLAB, there are a series of matrix operations versus array operations. Addition and subtraction for both arrays and matrices are done element by element. With other operations, for instance multiplication, linear algebra specifies how matrices are multiplied; it is not element by element multiplication.

Sometimes, you may want to use the element by element array operations. MATLAB separates matrix operations from array operations by using a dot notation in front of the operators. The following is a list and description of array operations. The corresponding matrix operations omit the dot.

 `.*` Element-by-element multiplication `./` Element-by-element division `.\` Element-by-element left division (for instance, if you have A\B, you will divide by A instead of B) `.^` Element-by-element power (for instance, to square all elements of A, you would write A.^2) `.'` Unconjugated array transpose

The following page provides some examples of the basic difference between matrix operations and array operations: arrayVersusMatrix.html.

### 2.11 Commands for Moving around in MATLAB

You may have already noticed that MATLAB provides you ways of cycling through commands you have already typed and editing those commands. A list of commands is on the bottom, left hand side, you can double click on any of those commands to repeat them.

In addition, you can use the up arrow or down arrow to move through previously typed commands.

There is a summary table of commands for editing on the command line available through MATLAB Help. You can also find it online by clicking on the following link and clicking on the links in the sequence indicated below: http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.html

• Getting Started
• Matrices and Arrays
• Controlling Command Window Input and Output

### 2.12 semicolon(;) functioning

Semicolon “;” has two main functionings:

• Define the end of row,  etc. A=[1,2;3,4].
• If you end a line with a semicolon ( ; ), Matlab runs the statement but does not display any output when you press the Enter or Return key. This is particularly useful when you generate large matrices.

## 4. Exercise

### Part 1

The following exercises are progressive. Create each array in the order specified in the instructions. Please record in a text file (or .m file) how you created each of the matrices.

1. Create the following three matrices in MATLAB:
```A =                B =                                   C =
22     5           17     9     2     1     3            1     0     0
4    11            6     4    11     9    16            0     1     0
13     2                                                 0     0     1```
2. Use A to create the following matrices:
```A =                  D =                 E =
22     5             66    15            22     1    13
1    11              3    33             5    11     2
13     2             39     6
```
3. Use B to create the following matrices:
```B =                                     F =
17     9     3     1     3               3     3    17
6     4     3     9    16              16     3     6
```
4. Use C to create the following matrices:
```C =                    C =                    G=               *
1     0                1     0                22    -5
0     1                0    -1                 1   -11
13    -2```
*Hint: this one uses A and C together

### Part 2

1. We have an image that has been stored in a .dat file (this is not the normal way of storing image data). The file is image.dat. Load this file into MATLAB. If you are curious about the image in the file, once you have loaded it, you can view it using: ```imshow(uint8(image)) ```
2. This image could be displayed with more of a "dynamic range". What this means is that there is more of a difference between the darkest value and the lightest value. For instance, if in our original the darkest value is 80 and the lightest value is 200, then the difference is 120. By extending the dynamic range, we create a difference greater than 120. We are going to apply the following function to the image:
`image(i,j)*k+c`
1. First, we need to find the minimum and maximum value.
• Store the minimum value in a variable called `imin`.
• Store the maximum value in a variable called `imax`.
• Just for the fun of it, calculate the mean and store it in a variable called `imean`.
2. Next, calculate `k=255/(imax-imin)`
3. Then, multiply the image by k (the first part of the formula above) and store the results in `image2`. This will spread out the dynamic range. You should notice that the difference between the largest and smallest value is now greater than it was before.
4. In order to bring 255 up to 255 (because of the error introduced by the negative values), we will do the following:
• Calculate `c=imin*k`
• Take the absolute value (`abs`) of `c` and store it in `c`
• Add `c` to `image2` (this will complete the second part of the formula). Store the results in `image3`.
3. If you are curious about your new results, you can use:
`figure, imshow(uint8(image3))`
The "`figure,`" will allow you to display a new figure so that you can see both `image` and `image3` at the same time.