Reading 1 PDF
Reading 1 PDF
School Of
Electrical, Computer &
Telecommunications Engineering
UOW
ECTE955
Laboratory Notes
Introduction to Matlab
Readings 1-4
Version: 1.0
This publication is copyright. The contents of this publication are strictly for the use of UOW, and should not be
transmitted externally, unless otherwise authorised in writing. Copyright ã UOW
ECTE955 Lab M. Shujau, L. C. Tran Page 1
SECTE Laboratory Notes
Document Control:
TABLE OF CONTENTS
INTRODUCTION ...............................................................................................................................................7
SCHEDULE AND FORMAT..............................................................................................................................7
LABORATORY ASSESSMENT .......................................................................................................................7
RESOURCES ....................................................................................................................................................7
READING 1 (Chapters 2 and 3 in the text book)...........................................................................................9
1. INTRODUCTION ...............................................................................................................................9
1.1. LABORATORY 1 – GETTING TO KNOW MATLAB .......................................................................9
1.2. MATLAB BASICS .......................................................................................................................... 10
1.3. WRITING SCRIPTS AND FUNCTIONS......................................................................................... 13
1.4. VECTORS AND ARRAYS ............................................................................................................. 15
1.5. ARRAY ARITHMETIC OPERATION ............................................................................................. 20
1.6. MATRIX INVERSION ..................................................................................................................... 21
1.7. LABORATORY-1 EXERCISES ..................................................................................................... 22
READING 2 (Chapters 4 and 5 in the text book)........................................................................................ 24
2. LOGICAL STATEMENTS, LOOPS AND MATLAB FUNCTIONS ................................................ 24
2.1. IF – ELSE – END STATEMENTS ................................................................................................... 24
2.2. LOGICAL OPERATORS ................................................................................................................ 26
2.3. “FOR LOOP” STATEMENTS ........................................................................................................ 26
2.4. THE “WHILE LOOP” ...................................................................................................................... 27
2.5. THE SWITCH STATEMENT........................................................................................................... 28
2.6. BREAK STATEMENTS.................................................................................................................. 29
2.7. MATLAB FUNCTIONS................................................................................................................... 30
Table of Figures
Table of Tables
Table 1: Order of arithmetic operation ....................................................................................................... 12
Table 10: Command for Reading and writing audio files ......................................................................... 51
Introduction
This laboratory is an introduction to the Matlab Programming environment which is an essential tool in
most courses in SECTE. It is expected that through these labs students will become familiar with the
Matlab programming environment and will gain necessary skills needed for other SECTE subjects which
require Matlab.
Acknowledgements and thanks are given to Pearson Education Inc. and the authors of
Engineering Computation with Matlab for the permission to use the text book resources for
education purposes.
Laboratory classes are held weekly and each lab session is 3 hours. The laboratories are practical based
exercises using Matlab.
Laboratory assessment
Each student should maintain an A4-sized workbook (usually called a logbook) and use it to record
analysis and comments for the pre-lab and post-lab tasks. The laboratory progress will be assessed by
the laboratory demonstrators upon presentation of their logbook. Further details about the assessment of
the laboratory exercises can be found on the subject outline.
Resources
Software
The laboratory requires MATLAB software. This software packages have been installed in the computers
in the lab rooms.
Student version of the MATLAB software can be purchased from the MathWorks website:
http://www.mathworks.com/academia/student_version/
Windows logon
The computers in the laboratory rooms (e.g. 35.129) might have multiple operating systems installed on
them. When you start the computers, a boot manager screen will appear. Use the arrow keys to select
“Windows” and then hit enter. You should login to using the username and password for your University
of Wollongong ITS/Web-mail account.
Data backup
You MUST backup your lab work regularly. The easiest way is to use your own USB disk(s). Backup in
two USB disks is safer than one USB disk as the USB disk might be lost or it might be affected by viruses.
You could also store the backup of your work on your email or your online drive (e.g., OneDrive, Dropbox,
Google Driver) if you have such cloud storages. It is the responsibility of students to make sure that your
works have been saved correctly and are ready to be used for the scheduled assessments in the subject.
Lab policy
All University of Wollongong laboratory procedures and guidelines must be followed at all times.
Prior to the end of the laboratory all students must cease working on their experiments, present their
logbook to lab demonstrators for marking, and log out of the computer.
Reading 1
1. Introduction
Matlab is a powerful language for technical computing. The synonym MATLAB stands for MATrix LABoratory.
Matlab combines computation, visualization and programming environments all in to one platform. It has a
complex data structure and has its own debugging and editing tools and supports object oriented
programming. It has built in routines which enable fast and easy computation of otherwise complex
calculations such as Fast Fourier Transforms (FFT). Results can be graphically visualized easily with easy to
understand and easy to use graphics commands. These sets of routines are grouped and packaged into tool
boxes; there are tool boxes for signal processing, control theory and many others from different areas of
engineering.
The labs presented here are designed for students with no prior experience with Matlab to become familiar
with Matlab and learn to use Matlab to solve application problems. The objective of these labs is to enable
students to quickly learn the basics steps. It is important that students understand that learning a new
language requires practice, hence the best way to learn fast is “ trying it yourself”.
It is advised that students get access to the recommended textbook “David M. Smith, Engineering
Computation with Matlab, 3rd Ed, Pearson” and spend as much time as possible practicing Matlab skills in
their own time. There are 4 readings in this lab note. All the laboratory questions in this lab manual are from
the recommended text book “David M. Smith, Engineering Computation with Matlab, 3rd Ed, Pearson” and are
in there original form as they appear in the original text.
When you open Matlab by double clicking the Matlab icon on your desktop the Matlab desktop will appear.
The Matlab desktop has four other windows in it which are:
Let us start using Matlab to do some simple tasks, the commands are entered in to the command window at
the command prompt (>>).
Let us start with a simple calculation, if we want to add two numbers let’ s say 5 and 4, at command prompt
we type
>> 5+4
ans =
9
Since we didn’t assign an output variable, Matlab assigned the output to the default variable ans which is
answer for short. If we decide to assign the output for the same operation to variable x then
>> x = 5+4
x=
9
Since variable x is assigned the value 9 from previous operation, the value of 2x will be calculated as
>> 2*x
ans =
18.0000
where * denotes the multiplication operation in Matlab. The variables in Matlab can be re-assigned and in this
example the output from the operation 2x will be assigned to x
>> x = 2*x
x=
18.0000
It is helpful to use meaningful names for variables as this would make it easy to follow when writing scripts.
Let’s try another example, this time we will create a variable called “ number” and assign the value 10 and then
divide the value by 2 and assign the value to another variable “output”.
>> number = 10
number =
10
>> output = number/2
output =
5
Here, every time a step is completed a result is seen. If we do not wish to see the intermediate results, we
can suppress the numerical output by putting a semi colon (;) at the end of the line.
>> number = 10;
>> output = number/2
output =
5
This time the output from assigning the value 10 to “ number” is suppressed. If you wish to see the value
assigned to “number” it can be seen in the workspace window. All the variables that are in use are displayed
in the workspace window.
If we wish to save the workspace variables of our Matlab session to a file, we can use the “save” command.
More details are mentioned later in Section 4.1.
ans =
25.9357
The results are very different with and without parentheses. It is very important that the order of arithmetic
operation is followed correctly to avoid ambiguity.
Here Matlab has displayed all the information about “cos” function and other functions that are related to “cos”
function in Matlab. It is worth noting the “doc cos” link which opens the online Matlab help manual, which is
much more comprehensive and gives examples of how to use the function. Another useful help tool is the
“lookfor” command which gives quick summary information about the function.
In addition to pre-defined functions, Matlab has many pre-defined constants such as:
Constant value
pi π = 3.14159……..
i and j √ 1
Inf infinity
NaN Not a number
Example 1:
Let the system of equations be:
2 3 =4
{ 3 4 =3
=1
We want to find the solution, named s, for the this system of equations
Example 2
The general form of a quadratic equation is:
=0
with the roots of equation given by
±√ 4
=
2
We want to create a function that will accomplish this:
- Save the function in the current directory and then call the function in the command line or inside
another function as follows:
The most basic element is Matlab is a Matrix. A matrix is 2 dimensional arrays consisting of m rows and n
columns. First we will look at vectors which are a special case of matrixes. There are two types of vectors,
namely row vector which is a matrix of (1×n) dimension and column vector which is a (m×1) matrix.
cvec =
1
2
3
4
5
A row vector can be converted to a column vector using the transpose command denoted by a apostrophe
(’). Let us convert our row vector “rvec” to a column vector:
>> cvec = rvec'
cvec =
6
7
8
9
0
A row vector with 10 elements with spacing of 1 is created. Here we do not have the control over how many
elements are in the vector.
By using the “linspace” command we can create a linear ly spaced vector between (and including) two numbers
we want. For example:
>> vec = linspace(1,10);
gives 100 points (default value) linearly spaced between 1 and 10. By introducing the number of points in to
“linspace” command we can get any number of points we want. For example:
>> vec = linspace(1,10,5)
vec =
1.0000 3.2500 5.5000 7.7500 10.0000
gives five points between 1 and 10.
In general, the command linspace(x1,x2,n) generates n points with the spacing of (x2 – x1)/(n – 1) between
any two consecutive points.
>> Mat(1:3,1)
ans =
1
4
7
>> Mat(1,1:3)
ans =
1 2 3
Similarly if we want to select part of the matrix we can use the colon operator.
>> Mat(1:2,1:3)
ans =
1 2 3
4 10 6
An empty matrix can be created using the empty square brackets ‘[ ]’. This matrix has the size 0 by 0.
>> empty = [];
>> size(empty)
ans =
0 0
ans =
1 2 3 4 9 10 11 12
5 6 7 8 13 14 15 16
Vertically
>> [MatA;MatB]
ans =
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
- A+B or B+A is true if the both matrixes A and B are of same size.
- A*B is true if number of columns of A equals number of rows of B
- A^2 is true if A is a square matrix and equals A*A
Important notes: A^2 is different from A.^2. The former is equal to A*A while the latter produces a matrix, each
element of which is the square of the corresponding element in A. The former is a matrix operation, while the
latter is an array operation (see more details in Section 1.5).
Array arithmetic operations are done on an element by element basis. This is different from the matrix
operation described before. The period character “.” is used to indicate the array operation. For array
operations the matrixes have to be of the same size. The command for the array operations are:
Operator Operation
.* Element by element multiplication
./ Element by element division
.^ Element by element exponentiation
ans =
36 36 36
54 54 54
72 72 72
>> A.*B
ans =
8 8 8
18 18 18
32 32 32
>> A/B
Warning: Matrix is singular to working precision.
ans =
NaN NaN NaN
NaN NaN NaN
NaN NaN NaN
>> A./B
ans =
2 2 2
2 2 2
2 2 2
Here we can see the difference in the results of performing matrix and array operations.
Important notes: the “inv” and “det” commands only work for a square matrix. Using these commands for a
rectangular matrix will cause a Matlab error message.
To calculate the inverse of a rectangular matrix, referred to as the Moore-Penrose inverse matrix, the “pinv”
command can be used. This command will be mentioned in more detail latter in Part B of this subject.
Self-Answer Questions
(Notes: self-answer questions will not be marked during prelab or postlab markings, but they might be helpful
for your tests and final exam. You should read the materials and try your best to answer these questions by
yourself)
1. What is the typical Matlab command that you would use to change a row (or column vector) into a
matrix (for example, from a vector [1, 2, 3, 4] into the matrix [1 2; 3 4])?
2. What is the typical command to convert a row vector (or column vector) to a column vector (or row
vector) (for example, from the row vector [1, 2, 3, 4] to the column vector [1; 2; 3; 4])?
3. What is the typical command to save texts in the command window of a Matlab session to a file?
4. What is the typical command to save workspace variables of a Matlab session to a file?
5. Given a matrix A. What is the main difference between A.^2 and A^2?
6. Given a matrix A. What is the main difference between A/3 and A./3?
From now on, students are strongly recommended to use Matlab Editor (press the keyboard shortcut Ctrl+N
to open it) to write Matlab programs. Remember to save your programs and backup them regularly.
1. You are given two sides of a triangle, a = 4.5 and b = 6. The angle between them is 35 degrees. Write
a script to find the length of the third side and the area of the triangle.
Hints: use the cosine rule for a triangle ( = 2 cos ). Area of a triangle is calculated as
= sin .
2. Write a script that validates the relationship between sin(u), cos(u), and tan(u) by evaluating these
functions at suitably chosen values of u.
Hint: Test the difference between sin(u)/cos(u) – tan(u)
3. For these exercises, do not use the direct entry method (i.e., do not enter by hand every element of
a vector) to construct the vectors, but write a Matlab script that does the following:
a. Construct a vector, name “evens”, containing all of the even numbers between 6 and 33,
inclusive of the end points (if they are also even).
Hint: 33 is not an even number, so 33 should not be included in the vector evens
b. Construct a vector, named “threes”, containing every third number starting with 8 and ending
at 38.
Hint: the vector “threes” need to include 8, 11, 14 etc.
c. Construct a vector, reverse, containing numbers starting at 20 and counting backwards by
one to 10.
d. Construct a vector, theta, containing 10 evenly spaced values between 0 and 2π.
e. Construct a vector, myZeros, containing 15 elements, all of which are zeros.
f. Construct a vector, random, containing 15 uniformly distributed random numbers between 1
and 12.
Hint: use the Matlab built-in function rand to construct the vector of uniformly distributed
random numbers within an interval [a, b]. See its syntax and example in the Matlab help.
5. Write a script to solve the following problems using only vector operations:
a. Assume you have two vectors named A1 and B1 of equal length and create a vector C1 that
combines A1 and B1 such that
C1 = [A1(1), B1(1), A1(2), B1(2), . . . . ,A1(end), B1(end)].
For example, if A1 = [2, 4, 8] and B1 = [3, 9, 27], C1 should contain: [2, 3, 4, 9, 8, 27]
b. Assume that you have two vectors named A2 and B2 of different lengths. Create a vector C2
that combines A2 and B2 in a manner similar to part a. However, if you run out of elements
in one of the vectors, C2 also contains the elements remaining from the longer vector.
For example, if A2 = [1, 2, 3, 4, 5, 6] and B2 = [10, 20, 30], then C2 = [1, 10, 2, 20, 3, 30, 4,
5, 6]; if A2 = [1, 2, 3] and B2 = [10, 20, 30, 40, 50], then C2 = [1, 10, 2, 20, 3, 30, 40, 50]
6. Write a script that takes a vector of numbers, A, and return a new vector B, containing the cubes of
the positive numbers in A. If a particular entry is negative, replace its cube with 0. For example, if:
A = [1 2 -1 5 6 7 -4 3 -2 0], B should be [1 8 0 125 216 343 0 27 0]