You are on page 1of 42

MATLAB Introduction

Elinor Tzvi, Stephen Oung

September 27, 2011


Contents

1 Back to Basics 3
1.1 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 Linspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Indexing Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Basic Math Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Element Specific Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.6 Common Built-in Math Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.8 Sum Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.9 Max, Min Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.10 Random Number Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.11 Mod function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.12 Practice/Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2 Matrices 9
2.1 Common Functions for Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2 Indexing Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.1 Linear indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.2 Finding Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3 Matrix Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.4 Matrix Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.5 Special functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.6 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.7 Exercises/Practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

3 Plotting 15
3.1 Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.2 EZplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.3 Multiple-Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.3.1 Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.3.2 Multiple-Plots Different Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.4 Figure Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.4.1 Line Styles & Colours . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.4.2 Figure Axis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.5 plot3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.6 Other Types of Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.7 Practice/Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

4 Loops and Logicals 23


4.1 Switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

1
4.2 If. . . elseif. . . else. . . end . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.3 Boolean Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.4 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.4.1 while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.4.2 do...while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.4.3 for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.4.4 break interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.4.5 continue interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.5 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.5.1 Example 1 - Automatic indexing of a vector . . . . . . . . . . . . . . . . . . . . . . 29
4.5.2 Example 2 - Prime Number Producer . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.5.3 Example 3 - Coin Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.6 Avoid Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.7 Exercises/Practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

5 Functions and Scripts 32


5.1 Scripts/M-files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5.1.1 Commenting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.1.2 Cell Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.2 Functional m-files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.2.1 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.3 Inheritance/Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.4 Loading from files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
5.5 Saving Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

6 Sample Problems 38
6.1 Problem 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
6.2 Problem 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

2
Chapter 1

Back to Basics

1.1 Vectors
Vectors are the main working data structure in MATLAB. They are a linear collection of elements which
can contain characters or numbers. They can span either row or column individually, or both (matrices
will discussed in the following weeks). Vectors can be created and stored in a single variable by using
spaces or commas between elements between square brackets.

Example 1 Manual Vector Creation. The elements of variable a is 1, 3, 5, 7, and 9


>> a = [1 3 5 7 9];
a = 1 3 5 7 9
>> a = [1, 3, 5, 7, 9];
a = 1 3 5 7 9

A second method of creating a vector is to use the : comma operator. The general structure is given
by:
vector = start : interval : end
Where the interval is the difference between elements in the array. If an interval is not specified, the
interval is defaulted to 1.

Example 2 : Operator Created Vector


>> a = 1:9
a =
1 2 3 4 5 6 7 8 9
>> a = 1:2:9
a =
1 3 5 7 9

1.1.1 Linspace

As opposed to stating the interval between samples, it is possible to state the number of samples between
start and end by using the function linsapce. The general form of this command is:
>> linespace(start, end, n)
which will generate n+1 equispaced points between the start and end variable, inclusive.

3
Example 3 Creating a vector with linspace
>> a = linspace(1, 10, 20)
a =
1.0000 3.2500 5.5000 7.7500 10.0000

1.2 Indexing Vectors


Indexing is the process of looking at a specified element in a vector or array. Individual or groups of
elements can be indexed at any particular time.

Example 4 Indexing through a vector


>> a =[1 3 5 7 9];
>> a(2)
ans = 3
>> a(2:4) %returns the 2nd and 4th elemeents
ans = 3 5 7
>> a(2:end) %end is a keyword that indicates the last element in the vector
ans = 3 5 7 9

1.3 Characters
Similar to a series of numbers that can be stored in a variable, a string of characters can also be saved in
a variable. To differentiate between a character string and a variable, the string must be surrounded by
apostrophes i.e. . Everything within the apostrophes will be stored in a separate element, including
spaces. Indexing through the character string is similar to indexing a vector.
It should also be noted that MATLAB is case sensitive. Storing a = foo is not the same as b =
Foo.

Example 5 A string of Characters


>> a = What a lovely string;
>> a(1:5)
ans = What

1.4 Basic Math Operators


All math operators use the same rules for vector/matrix operations (i.e. multiplication of two vectors, x
and y , the number of elements in the row of x must be the same as the number of elements in the column
of y ). Similarly for adding and subtraction, the number of elements of each vector must match.

4
Example 6 Basic math operators
>> a =[1 3 5 7 9];
>> b = [2 4 6 8 10];
>> a + b %Addition
ans = 3 7 11 15 19
>> b - a %Subtraction
ans = 1 1 1 1 1
>> a(1)*b(1) %Multiplication
ans = 2
>> a(1)/b(1) %Right Division
ans = 0.5
>> a(1)\b(1) %Left Division
ans = 2
>> b(1)^2 %Exponent
ans = 4

1.5 Element Specific Operator


As shown in the aforementioned, each variable is treated as a mathematical vector. But what if you
wanted to treat each element individually? In such cases, the . operator must be used.

Example 7 Dot Operator Specific Operations


a =[1 3 5 7 9];
>> a.^2
ans = 1 9 25 49 81
>> a.*2
ans = 2 6 10 17 18
>> a./0.1
ans = 10 30 50 70 90

1.6 Common Built-in Math Functions


As MATLAB is a high-level computing language, there are numerous built-in functions that are readily
available; they just need to be found and learned how to be used.
Some of the most commonly used trigonometric related functions are:
pi, sin(x), cos(x), tan(x), asin(x), acos(x), atan(x)
The data inputted or outputted will be in radians.

Example 8 Built-in Functions


>> sin(pi/2)
ans = 0
>> asin(1)
ans = 1.5708

Other commonly used functions are:


sqrt(x), exp(x), log(x), log10(x), abs(x)
Note: exp(x) and log(x) represents the natural exponential and logarithm respectively. i.e. exp(x)
is the same as ex , and log(x) is the same as loge (x) or ln(x).

5
1.7 Rounding
There are multiple ways for rounding data in MATLAB. The following are the most common methods
for rounding:
round(x) - Rounds the vector x to the nearest integer floor(x) - Rounds the vector x down, to
the nearest integer towards minus infinity ceil(x) - Rounds the vector x up, to the nearest integer
towards infinity fix(x) - Rounds the vector x to the nearest integer towards zero

Example 9 Rounding Functions


>> x = [-3.1416, 1.5718, 3.1416];

>> round(x)
ans = -3 2 3
>> floor(x)
ans = -4 1 3
>> ceil(x)
ans = -3 2 4
>> fix(x)
ans = -3 1 3

Unfortunately, the aforementioned functions only round to the integer, no decimal value is maintained.
Subsequently, if rounding with decimal paces is desired, there is a simple workaround, as shown.

Example 10 Workaround for rounding decimal values


>> x = 3.14159265;

>> round(x*100)/100
ans = 3.14

1.8 Sum Function


When the function sum(x) is applied to vector x, it will add up all its components. By default, the sum
function will add up all the elements in the row, though it is also possible to sum up all the elements in
the columns. To change the default, a second argument can be added to the function to force a particular
dimension.
>> sum(x, dimension)
The dimension can be denoted by using either 1 or 2.
1 represents the column elements
2 represents the row elements

6
Example 11 Sum Function
>> x = [-3.1416, 1.5718, 3.1416];

>> sum(x)
ans = 1.5718
>> sum(x, 1) %Sum up the column elements
ans = -3.1416, 1.5718, 3.1416
>> sum(x, 2) %Sum up the row elements
ans = 1.5718

1.9 Max, Min Function


As the name suggests, the max, min function provides the maximum and minimum values of a vector.
Although knowing just the maximum value in the vector may be sufficient, most of the time it is just as
important to know the location of the maximum value. This can be done by storing the values into two
variables as follows
>> [number, loc] = max(vector)
Similar to the sum function, the default column or row the function defulta to can be changed by
specifying it as a second argument.

Example 12 Max-min function


>> x = [1, 2, 4, 3, 2, 1];

>> [a b] = max(x);
a = 4
b = 3
>>[a b] = min(x);
a = 1
b = 1

1.10 Random Number Generator


There are two random number generator; rand and randn. Both rand produces random variables with
an even distribution, whereas randn produces random variables with a normal distribution.
Though in both cases, the function will produce a random decimal number with 4 significant digits
between the range of 0 to 1. The rand(m,n) produces an mxn matrix of random numbers, each of which
is ranging between 0 to 1, exclusively.

Example 13 Built-in Functions


>> x = rand
x = 0.8147

>> x = rand(2, 2)
x =
0.9058 0.9134
0.1270 0.6324

7
Calling the random function repeatedly will result in a different answer every time. This is very useful
for simulating probabilities.
For example, if we wanted to stimulate the throws of a dice, we would use the random number generator.
However, the rand function only returns a value between 0 and 1, and a dice only has numbers between
1 to 6. In order to return the proper values, the random number must be multiplied by 6 added by 1
then rounded down such that it only returns integers between 1 to 6.

Example 14 Simulating rolling a dice


>> dice = floor(1 + 6*rand)
dice =
3

1.11 Mod function


The mod function is the modulus after division, also know as the remainder. However this function
should not be confused with the remainder function, rem. The modulus function will only provide the
absolute value of the remainder after division i.e. the sign of the original input will be lost. Conversely,
the rem function will provide the sign of the original input.

Example 15 Modulus vs Remainder Function


>> x = -10; y = 3;
>> mod(x,y)
ans = 1
>> rem(x, y)
ans = -1

1.12 Practice/Exercises
1. Given the vectors a = [2, 4, 6, 8] and b = 1:5, what is the expected outputs for:

a(3) a(2:3) b(2) b(4:end)

2. Create a vector d that contains only even numbers spanning from 0 to 100
Create a vector g that is 11 units higher than elements of d
Create a vector e that is 2 times the element of d
Create a vector f that whose element of d is raised to the power of 1.7
3. Create a random generating equation that will only output values between -50 to 50;
4. Calculate the revenue given by: Prices = [10 20 30 40 50] Sales = [50; 30; 20; 10; 1]
5. Find the projection of vector a = [3.5355, 3.5355] onto b = [4.9497, -0.7071] Hint: dot
product: a b = |a||b|cos

8
Chapter 2

Matrices

Matrices, also known as Arrays, are the backbone of MATLAB. It will be the most commonly used
datatype in MATLAB programming. Therefore a good understanding of what they are and how to use
and manipulate them them effectively is a necessary skill.
As matrices should be familiar to all engineers, they are essentially a rectangular set of numbers, where
each entry is called an element. Those familiar with math expression, a matrix has the resemblance of
the following:

a1,1 a1,m
A = ... .. ..

. .
an,1 an,m
Similarly, in MATLAB it is possible to create 2-, 3- up to n- dimensional arrays. Some of the basic ways
of initializing an array is as follows:

Example 16 Initializing Matrices


>> A = [1, 2, 3; 4, 5, 6; 7, 8, 9]
A =
1 2 3
4 5 6
7 8 9
>> B = [1:3; 4:6; 7:9]
B =
1 2 3
4 5 6
7 8 9

As it can be seen in Example 2, initializing a matrix is very similar to initializing a vector. The only
difference is the use of a ; (semicolon) to indicate a new row in the array. Manually entering an array is
seldom used as it is only limited to creating 2-dimensional arrays. It is more common to use pre-defined
functions to create an array ahead of time and populate it, or to load a set of data from a file.

2.1 Common Functions for Matrices


As previously mentioned, all functions that are available for matrices, is also available for a vector (for
future reference, a vector is just treated as a one-dimensional array).

9
NaN(n, m) - creates an nxm matrix and populates it with a Not a Number symbol.
zeros(n,m) - creates an nxm matrix and populates it with 0s
ones(n,m) - creates an nxm matrix and populates it with 1s
eye(n) - creates an nxn identity matrix
It should also be noted that each of these functions are not only limited to 2 dimensions. If additional
arguments are added, additional dimensions are added to the matrix i.e.
NaN(n,m,p) - creates an nxmxp matrix
For simplicity, this document will only focus on 2- and 3-dimensional matrices. However all the functions
remain the same for higher dimensions

2.2 Indexing Matrix


Similar to indexing vectors, a set of numbers are used to index matrices; each number represents one
dimension. By convention, when indexing matrices, the first number will represent the row and the
second will be the column. It is possible to index more than just 1 element at a time; an entire column
or row, can be returned by using : (colon) instead of a number.

Example 17 Example
>> A = magic(3);
A =
8 1 6
3 5 7
4 9 2
>> A(2, 3)
ans =
7
>> A(1 , : )
ans =
8 1 6

2.2.1 Linear indexing

It is also possible to use a single number for indexing a multiple dimensional arrays, as shown be-
low:

a1,1 a1,2 a1,m a1 an+1 a(n1)m+1
a2,1 a2,2 a2,m a2 an+2 a(n1)m+2
A= . .. = .. ..

.. .. .. .. ..
. . . . . . .
an,1 an,m an a(n1)m+m
It should be noted that one of the most common error in MATLAB is indexing elements outside of the
dimension range. In such situations, MATLAB is throw back the following error:
??? Index exceeds matrix dimensions.

10
2.2.2 Finding Elements

Some of the most common reasons for using matrices is to store data and data-mining/manipulation. In
such cases, it is normal to search for when a particular element has reached a certain threshold. And
available function that will allow you to do this without creating a manual creating an algorithm, is to
implement the find function. i.e.
find(matrix booleanOperator threshold
The result of this function is the linear index value of each element within the array that is true for that
function. e.g.

Example 18 Two different ways of implemeting the find function


>> A = magic(3) >> [row, col] = find(A>5)
A = row =
8 1 6 1
3 5 7 3
4 9 2 1
>> indexValue = find(A > 5) 2
indexValue = col =
1 1
6 2
7 3
8 3

As shown, it is possible to have the find function return the row and column value of each element that
satisfies the condition statement. In such cases, each row for both returned variable will represent a single
value. However, as shown, with the example this will start to become more hectic as double the variables
will be produced. Subsequently, it is easier management to just use the linear index values.

2.3 Matrix Concatenation


Matrix concatenation is the process of joining small matrices into a single large matrix. The concatenation
operator is symbolized by the square brackets, the same ones used to create matrices or vectors. In fact,
by utillizing the square brackets, the program is just being told to put together the numbers together
and store it into a single variable. The same can be done with Matrices.
When concatenating matrices together, the dimension of the matrices being concatenated must be com-
patible. i.e. if matrices are being concatenated to the rows, then the number of columns of the ma-
trices must match. Similarly, if matrices are being added to the columns, the number of rows must
match.
If the columns or rows do not match, an error similar to
??? Error using ==> vertcat
CAT arguments dimensions are not consistent.
will be displayed.

11
Example 19 Example
>> A = magic(3);
>> B = magic(3);
>> C = [A ; B] %combine matrix B below A
C =
8 1 6
3 5 7
4 9 2
8 1 6
3 5 7
4 9 2
>> D = [A B] %combine matrix A beside B
D =
8 1 6 8 1 6
3 5 7 3 5 7
4 9 2 4 9 2

2.4 Matrix Parsing


Parsing is the process of extracting elements from the matrix such that only the useful information
remains. One of the most basic method is the brute force approach where you specific the exact elements
that should be saved in the new matrix e.g.

Example 20 Manual matrix parsing


>> A = magic(3)
A =
8 1 6
3 5 7
4 9 2
>> B = A(2:3,:) %saving only last two rows
B =
3 5 7
4 9 2

However this method is undesirable at times since additional variables are being created. Another
approach is to use empty concatenation operator ( [ ] ), which consists of the two brackets with no
content between them. e.g.

Example 21 Deleting a row through an empty concatenation operator


>> A = magic(3);
>> A(:,2) = [] %removing 2nd row
A =
8 1 6
4 9 2

The same concept can be applied to deleting a column.

12
2.5 Special functions
As matrices widely utilized in engineering, there are readily available functions in MATLAB that are
also commonly used in math.
matrix - The apostrophe ( ) indicates the transpose of the matrix
matrix ^-1 - As in math -1 indicates the inverse. The same can be achieved by using inv(matrix )
diag(matrix ) - Only the diagonal of the matrix will be returned
magic(n ) - A nxn matrix in which the sum of each row and each column is the same
eig(matrix ) - Returns both the eigenvalues and eigenvectors for the matrix
sort(matrix ) - Sorts the elements in the matrix in ascending or descending order*
triu(matrix ) - Returns the upper triangular matrix
tril(matrix ) - Returns the lower triangular matrix
det(matri ) - Returns the determinant of the matrix
*Note: The sort function will treat each row or column individually.
It should also be stated that any function that is available for a vector is also available for a matrix.
A vector and a matrix are the same; one should only be weary about ensuring that the dimensions are
compatible with the operator.

2.6 Examples

2.7 Exercises/Practice
1. Given the array A = [ 2 4 1 ; 6 7 2 ; 3 5 9], provide the commands needed to
(a) assign the first row of A to a vector called x1
(b) assign the last 2 rows of A to an array called y
(c) compute the sum over the columns of A
(d) compute the sum over the rows of A
(e) compute the standard error of the mean of each column of A
2. Given the arrays x = [1 4 8], y = [2 1 5], z = [2, 4, 2] and A = [3 1 6; 5 2 7; 2 3 5], determine which
of the following statements will correctly execute and provide the result. If the command will not
correctly execute, state why not

(a) x + y (e) b = [x ; y]
(b) x + A (f) c = [x ; y]
(c) x + y (g) A(:,2) =[]
(d) A - [x y z] (h) d = [A ; x ; y]

3. Solve this system of equations using Cramers rule. Solve the system using the black slash operator

13
(a) 2x + 4y - 2z = -6
6x + 2y + 2z = 8
2x - 2y + 4z = 12

(b) -6x - 2y + 2z = 15
-3x + 4y - 3z = 13
2x + 4y - 7z = -9
4. Create a 5x5 array such that the sum of the columns of the individual rows and columns equals to
their column/row number.

14
Chapter 3

Plotting

3.1 Plot
One of the biggest advantage of MATLAB is its ability to handle large quantities of data and displaying
it in graphical form. Plotting is one of the multiple way of graphically displaying data.
The plot function is simplest but also the most powerful function for displaying data
>> plot(x, y)
It is possible to exclude the x, variable and only use plot(y). However, in such cases the interval between
values will be evenly distributed to 1.

Example 22 Using the plot function


>> x = [1, 1.5, 2, 7, 8,8.5];
>> y = 0:0.1:0.5;
>> figure;
>> plot(x, y);
>> xlabel(x-Axis); ylabel(y-Axis);
>> figure;
>> plot(y);
>> xlabel(x-Axis); ylabel(y-Axis);

15
0.5 0.5

0.45
0.45

0.4
0.4
0.35

0.35
0.3

yAxis
y-Axis

0.25 0.3

0.2
0.25

0.15
0.2
0.1

0.15
0.05

0 0.1
1 2 3 4 5 6 7 8 9 1 1.5 2 2.5 3 3.5 4 4.5 5
x-Axis xAxis
(a) plot(y) (b) plot(x,y)

Figure 3.1: Take note that the difference between the two graphs is the x-axis. In (a) the data is plotted
such that there is single increment. In (b) the data is plotted using the data stored in x

3.2 EZplot
A second method for plotting can be accomplished using the function ezplot. Unlike the previous function
that plots data point, this function will plot an equation written in standard notation. The equation
must be written as a string and sent to the function. Calling ezplot(function) will plot the function in
the default domain of 2 < x < 2. The domain can be changed by adding an additional argument
when calling the function.

Example 23 ezplot Function


>> func = x + y^2;
>> figure;
>> ezplot(func, [-1, 1]);

x + y2 = 0
1

0.8

0.6

0.4

0.2

0
y

0.2

0.4

0.6

0.8

1
1 0.8 0.6 0.4 0.2 0 0.2 0.4 0.6 0.8 1
x

The main advantage of this function is its ability to allow for rapid prototyping of equations; so you
can see the general trends of the functions. For example this is a very popular symbol written in math
form.

16
Example 24 The dark knight
1 figure ;
2 axes ( Xlim , [ 7 7 ] , X t i c k , 7:7 , . . .
3 Ylim , [ 5 5 ] , Y t i c k , 5:5 , . . .
4 YtickL , , XtickL , , . . .
5 Ygrid , on , Xgrid , on , . . .
6 Xcolor , [ . 8 . 8 . 8 ] , Ycolor , [ . 8 . 8 . 8 ] ) ;
7 hold on
8 f 1 = ( x / 7 ) 2 s q r t ( abs ( abs ( x ) 3) / ( abs ( x ) 3) )+ . . .
9 ( y / 3 ) 2 s q r t ( abs ( y+3/7 s q r t ( 3 3 ) ) / ( y+3/7 s q r t ( 3 3 ) ) )1 ;
10 f 2 = abs ( x / 2 ) (3 s q r t ( 3 3 ) 7)x2/1123+ s q r t (1 ( abs ( abs ( x ) 2)1) 2 )y ;
11 f 3 = 9 s q r t ( abs ((1 abs ( x ) ) ( abs ( x ) 0.75) ) /((1 abs ( x ) ) ( abs ( x ) 0.75) ) ) 8abs ( x )y ;
12 f 4 = 3 abs ( x ) +0.75 s q r t ( abs ( ( 0 . 7 5 abs ( x ) ) ( abs ( x ) .5) ) / ( ( . 7 5 abs ( x ) ) ( abs ( x ) .5) ) )y ;
13 f 5 = 2 . 2 5 s q r t ( abs ( ( ( 0 . 5 x ) ( 0. 5+ x ) ) / ( ( 0 . 5 x ) ( 0. 5+ x ) ) ) )y ;
14 f 6 = 6 s q r t ( 1 0 ) /7+(1.5 0.5 abs ( x ) ) s q r t ( abs ( abs ( x ) 1/( abs ( x ) 1) ) . . .
15 6 s q r t ( 1 0 ) /14 s q r t (4 ( abs ( x ) 1) 2 )y ;
16
17 e z p l o t ( f1 , [ 8 8 3sqrt ( 3 3 ) /7 64 sqrt ( 3 3 ) / 7 ] ) ;
18 e z p l o t ( f2 ,[ 4 4 ] ) ;
19 e z p l o t ( f3 , [ 1 0.75 5 5 ] ) ;
20 e z p l o t ( f3 , [ 0.75 1 5 5 ] ) ;
21 e z p l o t ( f4 ,[ 0.75 0.75 2.25 5 ] ) ;
22 e z p l o t ( f5 , [ 0 . 5 0 . 5 5 5 ] ) ;
23 e z p l o t ( f6 , [ 3 1 5 5 ] ) ;
24 e z p l o t ( f6 , [ 1 3 5 5 ] ) ;
25
26 set ( get ( gca , c h i l d r e n ) , C o l o r , b , Linew , 2 )
27 t i t l e ( Batman ) ; xlabel ( ) ; ylabel ( )
28
29 x l b l ( 1 : 1 5 , 1 : 2 ) = ; x l b l ( [ 1 , 8 , 1 5 ] , : ) = [ 7 ; 0 ; 7 ] ;
30 y l b l ( 1 : 1 1 , 1 : 2 ) = ; y l b l ( [ 1 , 6 , 1 1 ] , : ) = [ 5 ; 0 ; 5 ] ;
31 axes ( Xlim , [ 7 7 ] , X t i c k , 7 : 7 , . . .
32 Ylim , [ 5 5 ] , Y t i c k , 5 : 5 , . . .
33 YtickL , y l b l , XtickL , x l b l , . . .
34 Box , on , C o l o r , none ) ;

Batman
5

5
7 0 7

17
3.3 Multiple-Plots
At times it is desirable to have multiple functions on the same plot; for instance to see which control
function would lead to a faster convergence, or to just to see if there is any relationship between different
equations. In these cases, it is possible to hold a figure such that each new plot will be plotted on the
same figure. The hold keyword keeps the current figure active until the hold is released. The axes would
change accordingly to accommodate visibility of both graphs.

Example 25 Using hold for multiple plots


>> n = linspace(-5, 5, 200);
>> figure;
>> plot(n, exp(-(n ).^2/0.5^2), b); %gaussian
>> hold on;
>> plot(n, exp(-(n ).^2/1^2), r); %gaussian

0.9

0.8

0.7

0.6

0.5

0.4

0.3

0.2

0.1

0
5 4 3 2 1 0 1 2 3 4 5

Figure 3.2: Two gaussian plots on the same figure

3.3.1 Subplots

A second method of displaying multiple graphs on the same figure is to use the subplot command. The
general form of this function is subplot(m, n, p), where the function will break up a figure into a mxn
array and return the handle for displaying a graph in the pth element.

Example 26 A visual example of how the subplot function divides a figure window
>> figure;
>> subplot(4, 2, 1)

18
Figure 3.3: A visual example of how the subplot function would divide the window, if the command subplot(4,
2, 1) was given. Box 1 would be the location of the graph.

As opposed to a single element, the subplot command can also be expanded by incorporating a vector
for the third element. This will allow you to directly control the size of a particular plot.

Example 27 Plotting multiple plots in the same figure window


>> figure;
>> subplot(2,2,1); ezplot(exp(-x.^2/0.5^2))
>> subplot(2,2,2); ezplot(exp(-x.^2/2^2))
>> subplot(2,2,3:4); ezplot(-exp(-x.^2/2^2))

exp(x2/0.52) exp(x2/22)

1 1
0.8 0.8
0.6 0.6
0.4 0.4
0.2 0.2
0 0
1 0.5 0 0.5 1 4 2 0 2 4
x x
exp(x2/22)

0
0.2
0.4
0.6
0.8
1
4 3 2 1 0 1 2 3 4
x

Figure 3.4: Using subplots to plot multiple figures of unequal sizes

3.3.2 Multiple-Plots Different Axes

As we saw in aforementioned methods, the figures will always try to plot the data using the same axes.
In some cases where we wish to see both graphs on the same plot but adjusted such that a direct overlap
of the data can be seen. There is no direct function that will allow this, as of MATLAB 2008a, however
there is a workaround by using the line and axes function.
By using the axes function we can define new sets of axes and where the x and y-axis locations can be

19
set (i.e. top, bottom, right, left). After setting where the new axis will be plotted, the line function can
be used to draw the function on the particular axis.

Example 28 Multiple graphs on a single figure


>> x = -20:0.1:20;
>> sinc = sin(x)./x; %first function
>> gaussian = exp(-(x).^2/5^2) %second function

>> figure; hold on;


>> hl1 = line(x,sinc,Color,r);
>> ax1 = gca;
>> set(ax1,XColor,r,YColor,r)
>> ax2 = axes(Position,get(ax1,Position),...
XAxisLocation,bottom,...
YAxisLocation,right,...
Color,none,...
XColor,k,YColor,k);
>> hl2 = line(x,gaussian,Color,k,Parent,ax2);

1 1

0.9
0.8
0.8

0.6 0.7

0.6
0.4
0.5
0.2
0.4

0 0.3

0.2
0.2
0.1

0.4 0
20 15 10 5 0 5 10 15 20

Figure 3.5: Multiple plots with adjusted axes. The color of the axis coorelates with the graph line colour

Because this method uses different axes handles to control plotting multiple functions, the figure cannot
be manipulated with the figure GUI without disrupting the figure. e.g. if you attempt to zoom in to a
particular region, only the last function that was graphed will be affected; the other function will remain
unchanged. So in order to utilize this method effectively, you must need to know ahead of time which
region you want to focus on and adjust the axes accordingly.
For now, treat this as a template, if this type of graphing is required, please refer to the help document
for the gca, set, and axes keyword.

3.4 Figure Formatting


In order for other readers to understand the figures, they need to be annotated with titles and adjusted
such that only the important trend is displayed.
There are two methods for formatting the figures; using command lines or using the figure GUI. As
the GUI is hopefully self-explanatory, the following will mainly focus on illustrating command line
manipulation.

20
3.4.1 Line Styles & Colours

The default line style for a figure is using a solid blue line. However this can be changed by introducing
a third argument into the plot function. For example, to plot a red dashed line the following command
can be used
>> plot(x, y, r--)
The first argument in the string is to specify the colour, and the second is the marker style. The possible
options for adjusting the line style can be seen in Table 3.1:

Colours Marker Style


y yellow . point
m magenta o circle
c cyan x cross
r red + plus
g green - solid
b blue * star
w while : dotted
k black -. dashdot
dashed

Table 3.1: Different properties that can be used for colourizing the graphs.

In the case of a point, circle, cross, plus, or star, the default line graph is replaced with a scatter plot
where the symbols are the data markets.

3.4.2 Figure Axis

There are multiple ways of changing the size of the figures axes. One of the most common way is to
simple use the axis function, which gives you direct control of the size of the axis. The function is
implemented the following way:
>> axis([xmin xmax ymin ymax])
This function should be called after the figure has been created. In most cases, this is sufficient for
adjusting the viewing size of the figure. However other functions such as turning off the visibility, or
simply using the computer to automate the axis size can also be performed. More information can be
obtained by typing in help axis in MATLAB, or by going here. For more advance methods of figure
control and manipulation please refer to Handle Graphics

3.5 plot3
Unfortunately 2D plots are sometimes insufficient and an addition dimension is required. MATLAB
provides multiple ways of visualizing 3D data. If a simple plot with just 3 dimensions is required, this
can be easily accomplished by using the plot3 function. This function is similar to the plot function in
the sense that the methods for figure formatting is the same. The function is called in the following
manner:
>> plot3(x, y, z, lineStyle)
where x, y, z, are all vectors and lineStyle is the stylization of the line, as described in 3.1

21
3.6 Other Types of Plot
Other common types of graphs that are available are bar and histograms.
bar(vector ) - plots a bar graph of the vector
hist(vector, bins ) - plots a histogram of the data where bins is an integer

3.7 Practice/Exercises
1. Plot the following functions within the domain {10 < x < 10}
Gaussian Function: 2
(xb)
f (x) = ae 2c2 for a=1, b = 0, c = 0.2
On the same plot, sin curve:
sin(x 90 ) and sin(x)
2. Using the histogram function, show the difference between the rand and randn function

22
Chapter 4

Loops and Logicals

When writing a script of code, there are multiple occasions where a segment of code is needed to be
repeated a number of times or a segment of code should only run if a certain condition is met. For
example if you want to find out if an equation has a convergence value, or if a function is only valid
within a certain domain.
In any programming language, there are multiple ways of implementing such methods. Some of the most
common methods are described below.

4.1 Switch Statements


One of the most basic methods for segmenting code is to use a switch statement. The general structure
of such statement is as follows:

Example 29 Example
switch switchExpression
case caseExpression
statements
case caseExpression
statements
otherwise
statements
end

The number of possible case used is indefinite. Depending on when the code is being used, there can
be as many as 100 different cases, or as few as 2. If different cases uses the same set of statements, it is
possible to combine multiple them together by using { } brackets. i.e.
case {2, 4, 6, 8, 10}
This method for code segmentation is strictly for separating different possible options. It is not possible
to place within the case expression vectors or any relationship operators such as < or >.
The otherwise statement is executed when the switchExpression does not match any of the caseExpres-
sion. That keyword may be omitted if necessary.
The following is a solid example of how switch statements can be used.

23
Example 30 In this example, the option is stored in the variable plotType. When the switch statement is
executed, it will compare the value stored in plotType against the possible cases. In this example, the value
matches the second case, and thus the first case is skipped, and only statements in the second case is executed
>> x = [12, 64, 24];
>> plotType = pie;

>> switch plotType


case bar
bar(x)
title(Bar Graph)
case {pie, pie3}
pie3(x)
title(Pie Chart)
legend(First,Second,Third)
otherwise
warning(Unexpected plot type. No plot created.);
end

Due to its inability to use relationship operators, it is seldom used for algorithm development. In most
cases, this will only be used when there is user interaction.

4.2 If. . . elseif. . . else. . . end


If statements are used to segment pieces of code and will include or exclude them based on a set of
conditions.

Example 31 General if statement


if (condition1 )
statements
elseif (condition2 )
statements
else
statements
end

A condition must be phrased as a true or false statement. If the condition is true, the expression within
the if block will run. If the condition is false, the expression will be skipped. If an elseif statement is
used, then the second condition is checked only if the first statement is false. If an else keyword is used,
the expression within this block will run only if every other condition is false.
The structure of the if statement is very flexible. It is possible to nest multiple if statements and
multiple elseif, and combine multiple conditions using boolean logical operators (described further in the
chapter).

24
Example 32 Multiple if, elseif statements. It is rumoured that you can only nest 256 if statements before the
program will crash.
if (condition1 )
...
if (condition)
...
statements
end ...
elseif (condition2 )
...
statements
...
elseif (condition3 )
...
statements
...
else
...
statements
...
end

It is easy to determine when to use if statements as its implementation can be said verbally e.g. if
money received is greater than cost, then calculate profit. This can easily be turned into code, as shown
below. Further detail about converting an idea to code will be explained further in a future lecture.

Example 33 Example
if(moneyReceived>cost)
profit = moneyReceived - cost;
end

4.3 Boolean Operators


Different operators are available for creating a condition.

Symbol Definition
< Smaller than
<= Smaller or equal than
>= Greater or equal than
== Equals to
= Not Equals to

Table 4.1: General boolean operators that can be used to compare statements

The boolean operators in Table 4.1 are used for comparison in the expression.

25
Symbol Defintion
|| Or
&& And
Not

Table 4.2: General Logical Operators

Logical operators in Table 4.2 are used for combing multiple condition statements. Unlimited number
of conditions can be placed together but must be separated by a logical operator. The way it is handled
for multiple conditions is dependent on which logical operator is used.

A B A&&B A||B A
1 1 1 1 0
1 0 0 1 0
0 1 0 1 1
0 0 0 0 1

Table 4.3: Boolean Table. 1 is true, 0 is false

One should be caution when using logical operators. In order for expected results when comparing
multiple statements, brackets should be employed to properly tell the computer which statements must
be compared. An example is shown below

Example 34 Brackets are important!


>> 1 && 1 || 0 && 0
ans = 1

>> (1 && 1 || 0) && 0


ans = 0

If we read the first statement in Example 4.3 from left to right, it would be expected that the answer
would return false i.e.
1 && 1 || 0 && 0 =
(1 && 1) || 0 && 0 = 1 || 0 && 0
(1 || 0) && 0 = 1 && 0
(1 && 0) = 0
However the nature of the logical operators are described as short circuited. i.e.
A && B - If expression A is false, expression B will not be calculated, and false will be returned
A || B - If expression A is true, expression B will not be calculated, and true will be returned
Subsequently, in Example 4.3 after the first && was calculated and true was obtained, the expressions
for the || was short-circuited and true was returned immediately. By implementing the brackets in the
2nd statement, the short-circuit behaviour is avoided, and effectively returning the proper answer.

4.4 Loops
As the name implies, a loop is a piece of code where it will start at a particular location and will repeat
itself until broken.

26
In the previous week, a very basic loop using the : operator, example ??, was already illustrated; the
colon operator would continuously increment the value until it reaches the maximum value. However, in
most cases, an incremental loop is insufficient. In most cases, a large chunk of code should be repeated
until some logical condition is satisfied; a condition that cannot be determined by stating the number of
times the chunk of code should be repeated.
For the more visually inclined, loops can described with the following flow chart

Figure 4.1: Flowchart of a while loop. Block A represents the condition for the loop. Block B represents the
chunk of code that would be executed

In general there are two types of loops while and for loops.

4.4.1 while

This an entry controlled loop; the condition for beginning the loop is checked at the beginning.

Example 35 General while Statement


while(condition)
...
statements
...
end

4.4.2 do...while

It should be noted that in other programming languages such as C++, Java, C, there is another variant
of the while loop. There is also the do...while condition loop. The difference with the former loop is

27
that this will still perform one iteration of the block epression. This is advantageous in some situations
if regardless of the condition, the code must be operated once.
This is considered an exit controlled loop.

4.4.3 for

for loops in MATLAB appear significantly different than any other programming language, but the
concept remains the same.

Example 36 General for loop


for variable = startValue : increment : endValue
...
statements
...
end

In other languages the general expression is shown as follows:


for(variable=startValue ; condition ; increment)
Unlike the previous loop, this loop was designed with a specific number of iterations in mind. If properly
understood and implemented, it is a very useful tool used in all programming languages.

4.4.4 break interrupt

In some cases, a loop must be exited before the predefined condition. In which case the keyword break
can be used. If the break condition is met, the lowest level loop that called the break statement will
stop. i.e. in the case of the Example ??, when the if statement is true, the second loop will exit, and
the first loop will then continue with the next iteration.

Example 37 Implementing break interrupts


for variable = startValue : increment : endValue %first for loop
for variable = startValue : increment : endValue %second for loop
...
if(variable == midValue)
break;
end
...
end

4.4.5 continue interrupt

In some cases, the code within the loop must be skipped, but the loop must continue its iterations. In
such cases the keyword continue can be used. If the continue condition is met, any code below the
continue statement will be skipped, and the following iteration will occur i.e. in the case of the Example
??, when the if statement is true, statements1 will not be performed for that iteration.

28
Example 38 Implementing break interrupts
for variable = startValue : increment : endValue
..
.
statements1
..
.
if(variable == midValue)
continue;
end
..
.
statements2
..
.
end

4.5 Examples
The examples for each of the possible loops was placed together at the end of the section because with
the available tools, both methods can perform the same actions. In the following examples different
methods for implementing loops will be shown

4.5.1 Example 1 - Automatic indexing of a vector

The problem: This problem asks the program to write a short algorithm that will be able to go through
a vector, and return all the positions of a particular value.

Example 39 Two possible ways of solving the same problem


Possible Solution 1: Possible Solution 2:
1 vector = [2 , 4 , 5 , 3 , 5 , 2 , 5 ] ;
1 vector = [2 , 4 , 5 , 3 , 5 , 2 , 5 ] ; 2 particularValue = 5;
2 particularValue = 5; 3 i = 1;
3 4
4 f o r i =1: s i z e ( v e c t o r , 2 ) 5 while ( i <= s i z e ( v e c t o r , 2 ) )
5 i f ( v e c t o r ( i ) == p a r t i c u l a r V a l u e ) 6 i f ( v e c t o r ( i ) == p a r t i c u l a r V a l u e )
6 disp ( s p r i n t f ( l o c a t i o n %d , i ) ) ; 7 disp ( s p r i n t f ( l o c a t i o n %d , i ) ) ;
7 end 8 end
8 end 9 i = i +1;
10 end

Output:
location 3
location 5
location 7

As shown in Example 5.3, there are multiple ways of solving the exam same problem. Due to the large
variety of tools available at the programmers disposal, loosely speaking there is no correct way of pro-
gramming a solution. In industrial programming, there are certain programming patterns and methods
implemented to increase efficiency however those topics are beyond the scope of this course.

29
4.5.2 Example 2 - Prime Number Producer

The problem: This problem asks the programer to devise an algorithm that prints the numbers from 1
to 10. But for prime numbers print Narf instead of the number and for the multiples the prime print
Zort.

Example 40 Possible solution finding prime numbers and replacing them with text
1 STARTNUMBER = 2 ; Output:
2 ENDNUMBER = 1 0 ; Narf
3 PRIME = Narf ;
4 MULTIPLE = ZORT ;
Narf
5 4
6 f o r i = STARTNUMBER:ENDNUMBER Narf
7 divisor = 2; 6
8 factors = 1;
9 prime = t r u e ; Narf
10 f o r j = 2 : f l o o r ( sqrt ( i ) ) 8
11 i f (mod( i , j ) == 0 ) 9
12 prime = f a l s e ; 10
13 break ;
14 end
15 end
16
17 i f ( prime )
18 disp ( Narf ) ;
19 else
20 disp ( i ) ;
21 end
22 end

4.5.3 Example 3 - Coin Machine

The problem: This problem asks the programer to devise an algorithm that, when given any monetary
amount, calculates the least amount of coins that would be able to provide the specified amount.
Note: Before any programming is done, for larger scale programs, it is always nice to think before
writing anything down. This will give direction to the code as oppose to blind programming, which can
lead to scenarios not being fully thought out and other disasters.
Approach: One of the most basic approach to this problem is starting with the largest coin denomination
find out the largest multiple that is smaller than the desired amount. If there is a remainder, use the
next largest coin denomination.

30
Example 41 A possible solution to the coin vending machine problem
Input: Output
2.000000x 1
1 amount = 3 . 4 8 ; %s t a r t i n g v a l u e 1.000000x 1
2 coins = [2 , 1 , 0.50 , 0.20 , 0 . 1 0 , . . . 0.500000x 0
3 0 . 0 5 , 0 . 0 2 , 0 . 0 1 , 2 ] ; %c o i n denomination
0.200000x 2
4 coinValue = 0;
5 0.100000x 0
6 f o r i = 1 : s i z e ( c o i n s , 2 ) %c h e c k each denomination 0.050000x 1
7 counter = 0; 0.020000x 1
8 while ( c o i n V a l u e+c o i n s ( i )<amount )
9 coinValue = coins ( i ) + coinValue ;
0.010000x 0
10 c o u n t e r = c o u n t e r +1; 2.000000x 0
11 end
12 disp ( s p r i n t f ( %f x %d , c o i n s ( i ) , c o u n t e r ) ) ;
13 end

4.6 Avoid Loops


Because the way MATLAB was designed, loops are generally bad and severely reduce the efficiency of
the program. Subsequently it is encouraged, when programming MATLAB, to reduce the number of
effective loops. In some cases, this can be done easily, and in other cases it requires some ingenuity.

4.7 Exercises/Practice
1. Find out the 1000th number in the fibonacci sequence
2. Rewrite the program described in Example 4.5.2 using only while loops with modifications that
only prime numbers are displayed; print out the first 100 prime numbers
3. What is the largest sum of 5 consecutive digits? What is the largest product of 4 consecutive
numbers? What is the smallest sum of 3 consecutive digits?
s = 1234567890987654321;

31
Chapter 5

Functions and Scripts

Up until now, MATLAB was utilized by typing commands directly into the command window, or was
written in notepad then copied into the workspace. For small pieces of code, this is fine, however for
more complex tasks using the command window is simply insufficient. Thus in MATLAB, it is possible
to store the typed commands into a file, and tell MATLAB to get all its input commands from that
particular file. This type of file is called an M-file; the reason for this is due to its .m extension. As the
previous sections described how to turn MATLAB into an oversized scientific calculator, the following
sections will start to expose how MATLAB can double as a programming language and can satisfy most
programmers need when prototyping or developing an algorithm.

5.1 Scripts/M-files
Scripts typically contain a sequence of commands to be executed in sequence by MATLAB when the
filename is entered into the command window. Scripts, or m-files, are the heart of MATLAB and one
should start to familiarize themselves with writing scripts. New m-files can be easily created by going to
File-M-File. Doing so will bring up an m-file editor window. Within this window, you will be able to
be able to write all the typical commands as you would in the command window.
The code within the script will function sequentially, as it did when the command window was used to
calculate; all the commands will be read sequentially from top to bottom.
In the end, in order to run the script, the m-file must be saved, and the working directory of MATLAB
must be changed to the location of the m-file. The filename cannot be a function or keyword familiar
to MATLAB and cannot contain any spaces. Following this, the script can then be executed by simply
typing the name of the m-file in the command window.

Example 42 Executing an m-file


myFirstMFile.m
disp(Hello World!)

Command Window:
>> myFirstMFile
Hello World!

32
5.1.1 Commenting

It is common practice when writing scripts to comment the code. Commenting serves the purpose of
allowing the programmer to understand the code when they review it. It allows the programmer to
annotate their code with regular text that will not affect the actual program. Comments can vary from
augmenting program code with basic description to generating external documentation. In MATLAB,
comments are enabled by using the percent sign %.

Example 43 Commenting code


% Series1.m
% Simon Gisch
% 01/11/10
% Signals and Systems in Medicine Lab WS 10/11

% Exercise 1 - Develop the mod function


dividend = 10;
divisor = 3;
a = dividend-divisor*floor(dividend/divisor); %calculate modulus

It is common malpractice to comment every line of code. As variables should be named with some type of
significance, many of the basic lines can remain uncommented. For instance in Example 5.1.1, comment-
ing the line could have been avoided by using a more significant name than a, such as remainder.

5.1.2 Cell Programming

In large programs or scripts, it is common to modularize, or separate the code at logical points so the
data processed up until that point can be visualized first before proceeding. MATLAB has a useful
feature in their m-file editor that allows this by simply adding %% only. If text is beside the %% then
the editor will treat the line as a regular comment.

Example 44 MATLAB Cell Mode


x = linspace(0,2*pi,200);
f1 = sin(x); %output
plot(x, f1)

%%
%% The start of the second cell
n = length(f1);
mean = sum(f1) / n; %average
stdev = sqrt(sum((f1 - mean).^2)/n); %standard deviation

%%This does not make a new cell


hold on;
plot(x, mean, k-);
plot(x, stdev,r-);
plot(x, -stdev,r-);

33
5.2 Functional m-files
As it was already shown, MATLAB has a wide array of functions readily available, such as sin and plot.
Though not all possible functions are already preprogrammed into MATLAB; in some cases, application
specific functions are required. MATLAB has very specific syntax for declaring and defining a function.
Functional M-files must have the same name as the function name. The definition of a function must
start with the keyword function followed by the output variables (s), equal sign, name of the function,
the input variables(s). It is also possible to design functions to have no input or output arguments. The
following is a valid function definition line for a function name stats that takes in the input data, and
returns the output stDev and mean

Example 45 MATLAB creating function m-files


stats.m
function [stDev, avg] = stats(data)
avg = sum(data)\length(data);
stDev = sqrt(sum((data - mean).^2)/n); %standard deviation

someOtherFile.m
x = linspace(0,2*pi,200);
sinData = sin(x); %output
tanData = tan(x); %output

[sinSTD, sinAVG] = stats(sinData);


[tanSTD, tanAVG] = stats(tanData);

The use of function is to mainly simplify repetition of the same code in ones script. It also makes the
code easier to read when the code is modularized into various functions.

5.2.1 Recursion

By knowing functions, a new concept of programming can be introduced, recursion. Recursion is a sinister
function that essentially calls itself until a kill statement is met. The following is a visual example of
recursion. Although it may seem a highly specialized function, it occurs frequently, especially in math.
For example the Fibonacci sequence is a recursive algorithm. By definition, the first two Fibonacci
numbers are 0 and 1, and each subsequent number is the sum of the previous two i.e.
fn = fn1 + fn2 , f0 = 0, f1 = 1
In terms of programming, the general style for a recursive algorithm is the following:

Example 46 General recursion algorithm


function [output] = recursion(input)

if (output satisfies a kill statement)


return output
else
output = recursion(output)
return output

34
Figure 5.1: A visualization of recursion. Consider a tow truck as a function whose purpose is to tow a car. In
this image, the tow truck function was called three times until a car was actually towed.

It is really important to emphasize on the fact that any algorithm using recursion must employ a kill
condition. Otherwise, the algorithm will run indefinitely, and eventually crash.
To give an example of a recursion algorithm, the following an example of how the recursion can be used
to sort an array.

Example 47 Two possible ways to solve the same problem


A = rand(500,1);

Trivial Solution: Recursive Solution:


1 function [ a r r a y ] = r b u b b l e S o r t ( a r r a y , count
, done )
1 function [ s o r t e d A r r a y ] = b u b b l e S o r t ( a r r a y , 2
count , done ) 3 i f ( done )
2 4 done = t r u e ;
3 sortedArray = array ; 5 f o r k = 1 : count 1;
4 n=length ( a r r a y ) ; 6 i f ( a r r a y ( k ) > a r r a y ( k+1) )
5 f o r j = 1 : 1 : n1 7 done = f a l s e ;
6 f o r i = 1 : 1 : n1 8
7 i f s o r t e d A r r a y ( i )>s o r t e d A r r a y ( i +1) ; 9 temp = a r r a y ( k+1) ;
8 temp=s o r t e d A r r a y ( i ) ; 10 a r r a y ( k+1) = a r r a y ( k ) ;
9 s o r t e d A r r a y ( i )=s o r t e d A r r a y ( i +1) ;11 a r r a y ( k ) = temp ;
10 s o r t e d A r r a y ( i +1)=temp ; 12 end
11 end 13 end
12 end 14 e l s e
13 end 15 return ;
16 end
17
18 a r r a y = r b u b b l e S o r t ( a r r a y , count , done ) ;

5.3 Inheritance/Hierarchy
Inheritance is a feature in programming that allows the programer to reuse code. Simply speaking,
inheritance allows the use of variables created higher up in the program by the nested control statements.
Conversely, the variables created in nested control statements cannot be inherited/used by the parent
control statement. As an analogy, in a family situation, if the parents are multi-millionaire, their children

35
will most like inherit all their wealth when they pass on. Subsequently, it is impossible for the parents
to inherit anything from their child, unless the unfortunate happens and the child passes away before
the parent.
In real programming, inheritance can cause many problems and requires a lot of pre-planning before
hand. However luckily with MATLAB inheritance does not play a big role since at every point in the
main working file, MATLAB will save the the variable whenever it is created. The only case in which
inheritance will play a roll is when functions are being used. Functions are treated as a complete black
box for the user. The only interaction between the function and the user will be the variables that are
being sent in as arguments or being returned.

Example 48
veryImportantFunction.m
1 function [ ou t p u t V a l u e ] = v e r y I m p o r t a n t F u n c t i o n ( i n p u t V a l u e )
2
3 v e r y I m p o r t a n t V a r i a b l e = rand ; %S t o r e d o n l y l o c a l l y
4 o u t p u t V al u e = i n p u t V a l u e . 2 / ( v e r y I m p o r t a n t V a r i a b l e i n p u t V a l u e ) ;
5
6 disp ( o u t s i d e F u n c t i o n ) ; %w i l l c a u s e an e r r o r Unde fined f u n c t i o n or v a r i a b l e

mainFile.m
1 clear a l l ; clc ;
2 outsideFunction = 200;
3 doSomething = v e r y I m p o r t a n t F u n c t i o n ( o u t s i d F u n c t i o n ) ;
4
5 disp ( doSomething ) ;
6 disp ( v e r y I m p o r t a n t V a r i a b l e ) ; %w i l l c a u s e an e r r o r Und efined f u n c t i o n or v a r i a b l e

5.4 Loading from files


A big advantage of MATLAB is its compatibility of reading data files from most measurement programs.
In most data collection programs now, the data can be exported as a regular text file. In such cases, the
data will be either space delimited, or comma delimited, i.e. the data points are separated by either a
space or comma. Such formats can be easily read by MATLAB with the load command.
To load a file, the file must be in MATLABs current workspace.
>> variableName = load(filename )
All the data from the file

5.5 Saving Workspace


Prototyping complex algorithms in MATLAB can incorporate long and arduous trial-and-error processes
that may or, more probably, may not involve a script. Thus reproducing the same result after hours of
work may not seem feasible in a short amount of time. Subsequently, MATLAB allows you to save all
the variables into a file and can be loaded latter when needed.
To save a workspace, the following command is typed into the command window:

36
Example 49 Loading data from a text file
dataFile.txt
3.40 6.70
7.70 8.70
7.30 5.30
6.90 1.20
4.60 1.80

Command Window
1 >> data = load ( data . t x t ) ;
2 >> data
3 ans =
4 3.40 6.70
5 7.70 8.70
6 7.30 5.30
7 6.90 1.20
8 4.60 1.80

>> save(filename)
This command will save all the variables from the current workspace to a binary MAT-file.
To load a workspace, the following command is typed into the command window:
1. Write a function to do determine prime factors given an input.
2. Print out a function the largest prime factors of the number 159807433

37
Chapter 6

Sample Problems

6.1 Problem 1
Given two signals; X, a square input to the LTI system and Y, the impulse response of the system. We
would like to observe the output from that system. In the second stage we would like to have more
samples of the output (factor of 3). How to go about it?

1 , -1 t 1
x(t) =
0 , t 1


t+1 , -0.5 t 0
x(t) = t + 1 , 0 t 0.5
0 , t 1

We break it down to intermediate steps:


1. Create the signals in Matlab
(a) Specify a time vector
(b) In order to better visualize my signals: present the two signals in one figure
2. Calculate the convolution between the signals. There are 2 ways to go about it:
(a) Using the built-in Matlab function
(b) Doing it using the Trapezoidal approximation of the convolution integral
To reach the next step we will follow the different sub steps:
1. Present the resulted signal as discrete
2. Create a new vector that contains only the non-zero values
3. Insert 2 zeros in between the samples in the convolved signal.
4. Present the resulted signal as discrete.
5. Use interpolation to get the values in between the original samples.
(a) Try different types of interpolation methods
(b) Present the resulted signals in one figure for comparison

38
Example 50 Sample solution for Sample Problem 1
1 x = i n l i n e ( 1 . ( t>=1&t <=1) ) ;
2 y = i n l i n e ( ( t +1) . ( t >=0.5&t <0)+(t +1) . ( t>=0&t <0.5) ) ;
3 t = 2 : 0 . 0 0 1 : 2 ; %c r e a t i n g time v e c t o r f o r s i g n a l s
4
5 figure ;
6 subplot ( 2 , 1 , 1 ) ;
7 plot ( t , x ( t ) ) ;
8 y l i m ([ 1 2 ] ) ;
9 xlabel ( t ) ;
10 ylabel ( x ( t ) ) ;
11
12 subplot ( 2 , 1 , 2 )
13 plot ( t , y ( t ) ) ;
14 y l i m ([ 1 2 ] ) ;
15 xlabel ( t ) ;
16 ylabel ( y ( t ) ) ;
17
18 figure ;
19
20 dtau = 0 . 0 0 5 ;
21 tau = 2: dtau : 2 ;
22
23 ti = 0;
24 tvec = 2:.1:2;
25 con = NaN zeros ( 1 , length ( t v e c ) ) ; % Prea l l o c a t e memory f o r s p e e d
26 for t = tvec ,
27 t i = t i +1; % Time i n d e x
28 xy = x ( ttau ) . y ( tau ) ;
29 con ( t i ) = sum( xy . dtau ) ; % T r a p e z o i d a l a p p r o x i m a t i o n o f c o n v o l u t i o n i n t e g r a l
30 plot ( t v e c , con , t v e c ( t i ) , con ( t i ) ) ;
31 xlabel ( t ) ;
32 ylabel ( o ut pu t ( t ) = \ i n t y ( \ tau ) x ( t \tau ) d\ tau ) ;
33 axis ( [ tau ( 1 ) tau ( end ) 1.0 2 . 0 ] ) ;
34 end
35 t i t l e ( o ut pu t ( t )=x ( t ) y ( t ) )
36
37 figure ;
38 stem ( t v e c , con )
39 xlabel ( t ) ;
40 ylabel ( o utpu t ( t ) ) ;
41 title ( discrete representation )
42
43 t r u e c o n=con ( con =0) ;
44 t v e c 2=t v e c ( con =0) ;
45 figure ;
46 stem ( t v e c 2 , t r u e c o n )
47 xlabel ( t ) ;
48 ylabel ( o utpu t ( t ) ) ;
49 t i t l e ( truncated s i g n a l )
50
51 u p s a m p f a c t o r =3;
52 upcon=upsample ( t r u e c o n , u p s a m p f a c t o r ) ;
53 t v e c 3=linspace (min( t v e c 2 ) ,max( t v e c 2 ) , length ( upcon ) ) ;
54 figure ;
55 stem ( t v e c 3 , upcon )
56 xlabel ( t ) ;
57 ylabel ( o utpu t ( t ) ) ;
58 t i t l e ( upsampled s i g n a l )
59
60 s t r i n g a r r ={ s p l i n e c u b i c n e a r e s t l i n e a r } ;
61 figure ;
62 i n t e r p c o n=NaN zeros ( length ( s t r i n g a r r ) , length ( upcon ) ) ;
63 f o r i =1: length ( s t r i n g a r r )
64 i n t e r p c o n ( i , : ) = interp1 ( t v e c 2 , t r u e c o n , t v e c 3 , s t r i n g a r r { i } ) ;
65 subplot ( 2 , 2 , i )
66 stem ( t v e c 3 , i n t e r p c o n ( i , : ) )
67 xlabel ( t ) ;
68 ylabel ( o ut pu t ( t ) ) ; 39
69 t i t l e ( s t r c a t ( I n t e r p u l a t e d S i g n a l , : , s t r i n g a r r { i } , Method ) )
70 end
6.2 Problem 2
In the attached text document there is some information about electrode placement in an image. Un-
fortunately the image is lost and you would like to retrieve the information automatically with the help
of MATLAB.
The text contains coordinates for electrode placement on a brain image. Your assignment is to retrieve
the information including the exact number of the electrode and produce a plot showing the exact location
of each electrode.
This is an example for the information about electrode 1:
x="236.9577"
y="340.65842"
id="text3105"><tspan
sodipodi:role="line"
id="tspan3107"
x="236.9577"
y="340.65842">1</tspan></text>
Hints:
1. Pay attention that the coordinate information appears twice!
2. The number of the electrode appears immediately after the y coordinate
Methods in solution:
1. Open the text document and go over the different coordinate information
2. Recognize a pattern and use a loop to read the information into a matrix
3. Draw a circle for each of the electrodes using the coordinate information point out the numbering
of the electrodes

40
Example 51 Sample solution for Sample Problem 2
1
2
3
4
5 A=i m p o r t d a t a ( e l e c i n f o . t x t ) ; %image as a t e x t f i l e to read the e l e c t r o d e information
6 e l e c t r o d e n u m b e r =64;
7
8 %s e a r c h i n g f o r x l o c a t i o n s
9 i n d =2;
10 x l o c a t i o n s=zeros ( e l e c t r o d e n u m b e r , 1 ) ;
11 p a t t e r n= x= ;
12 k = s t r f i n d (A, p a t t e r n ) ;
13 f o r i =1: length ( k )
14 i f isempty ( k{ i } )
15 l o c=k{ i } ; %l o c a t i o n o f x c o o r d i n a t e i n s i d e t h e s t r i n g
16 x l o c a t i o n s ( i n d )=s t r 2 d o u b l e (A{ i } ( l o c +4: l o c +10) ) ;
17 i f x l o c a t i o n s ( i n d )= x l o c a t i o n s ( ind 1)
18 i n d=i n d +1;
19 end
20 i f i n d==e l e c t r o d e n u m b e r+2
21 break ;
22 end
23 end
24 end
25 x l o c a t i o n s=x l o c a t i o n s ( 2 : end ) ;
26
27 %s e a r c h i n g f o r y l o c a t i o n s & e l e c t r o d e numbering
28 clear elec num ;
29 i n d =2;
30 i n d 2 =1;
31 y l o c a t i o n s=zeros ( e l e c t r o d e n u m b e r , 1 ) ;
32 p a t t e r n= y= ;
33 k = s t r f i n d (A, p a t t e r n ) ;
34 f o r i =1: length ( k )
35 i f isempty ( k{ i } )
36 l o c=k{ i } ; %l o c a t i o n o f y c o o r d i n a t e i n s i d e t h e s t r i n g
37 numloc1=s t r f i n d (A{ i } , > ) ;
38 i f isempty ( numloc1 )
39 numloc2=s t r f i n d (A{ i } , < ) ;
40 e l e c n u m ( i n d 2 )=s t r 2 d o u b l e (A{ i } ( numloc1 ( 1 ) +1: numloc2 ( 1 ) 1) ) ;
41 i n d 2=i n d 2 +1;
42 i f length ( e l e c n u m )==e l e c t r o d e n u m b e r
43 break ;
44 end
45 end
46 i f y l o c a t i o n s ( i n d )= y l o c a t i o n s ( ind 1)
47 i n d=i n d +1;
48 end
49 y l o c a t i o n s ( i n d )=s t r 2 d o u b l e (A{ i } ( l o c +4: l o c +10) ) ;
50 end
51 end
52 y l o c a t i o n s=y l o c a t i o n s ( 2 : end ) ;
53
54 e l e c t r o d e i n f m a t =[ elec num x l o c a t i o n s y l o c a t i o n s ] ;
55
56 %p l o t t i n g
57 m i n l o c v a l= min(min( e l e c t r o d e i n f m a t ( : , 2 : 3 ) ) ) ;
58 m a x l o c v a l= max(max( e l e c t r o d e i n f m a t ( : , 2 : 3 ) ) ) ;
59 figure ;
60 plot ( y l o c a t i o n s , x l o c a t i o n s , o ) ;
61 axis ( [ m i n l o c v a l 50 m a x l o c v a l +50 m i n l o c v a l 50 m a x l o c v a l +50])
62 f o r i =1: length ( y l o c a t i o n s )
63 text ( y l o c a t i o n s ( i ) +5 , x l o c a t i o n s ( i ) +5 ,num2str ( e l e c t r o d e i n f m a t ( i , 1 ) ) , C o l o r , [ 1 0
0])
64 end
65 t i t l e ( e l e c t r o d e s number and l o c a t i o n i n an image )
66 xlabel ( x ) ;
67 ylabel ( y ) ; 41

You might also like