DSP 20 Chapter 2
DSP 20 Chapter 2
Introduction to MATLAB
MATLAB [Mat20a] stands for MATrix LABoratoy and originally was written to do intensive
matrix computation. MATLAB is the software we will be using for the practical component of
this course. Later, it became a general purpose software to carry out all kinds of computations
in the scientific world, especially in engineering. MATLAB is currently a high-performance
language for scientific and technical computing. It integrates computation, visualization, and
programming environment. From a programming standpoint, it has all a programmer needs
and wishes for, from advanced data structures to powerful control flow and commands, from
rich code libraries to object-oriented programming. Also worth mentioning is the toolboxes
available in MATLAB. They are built-in routines for specific computation needs. At the user’s
disposal, there are toolboxes for statistics and machine learning, text analytics, MIR (music
information retrieval), symbolic math, and more. By taking this course and learning its content,
the student will be in contact with a professional tool for engineering.
This chapter on MATLAB is intended as a crash course, where the material will be taught
more by doing than by describing. MATLAB has a very complete online help [Mat20b]. The
student can get many examples from it and we will make reference to it as needed.
The following list provides excellent books and references for learning MATLAB: [PI10],
[Att13], [Pro16], [PV10]. In Spanish a thorough and clear textbook is [OSB00].
MATLAB can be obtained from the UPM website by any student officially enrolled in this
course; follow the instructions in the Moodle system.
7
8 Introduction to MATLAB
As a default output variable MATLAB uses a variable named ans, which is a short for answer, to
store the results of the current calculation. The variable is overwritten when another calculation
is made.
As in math, variables in MATLAB are symbols that represent arbitrary elements of a set;
this set can be formed by numbers, matrices, strings, or other sets. Variables can be assigned
on the spot.
1 >> x=3∗(2 1)+5/3 exp ( 2 )
2 x =
3 2.7224
All current variables defined are shown on the working space located on the top right of the
MATLAB window; see Figure 2.1. Variable assignment is made by using the symbol =.
Logical comparisons are carried out by writing A ==B, where A, B are two functions return
a Boolean value; this operator only checks for equality. Variable names in MATLAB are case-
sensitive. A valid variable name starts with a letter, followed by letters, digits, or underscores
If a mistake is made, for example, an expression entered incorrectly, MATLAB will return a
message error. If we type an expression with the product symbol ⇤, we obtain the following
message.
1 >> 3x+1
2 3x+1
3 ?
4 E r r o r : I n v a l i d e x p r e s s i o n . Check f o r m i s s i n g m u l t i p l i c a t i o n o p e r a t o r
, m i s s i n g o r unbalanced d e l i m i t e r s , o r o t h e r sy nt ax e r r o r . To
5 c o n s t r u c t m a t r i c e s , u se b r a c k e t s i n s t e a d o f p a r e n t h e s e s .
6
1 >> 2/(3+4) ∗5
2 ans =
3 1.4286
4 >> 2/3+4∗5
5 ans =
6 20.6667
7 >>
Another important aspect in MATLAB is numerical precision. By default the system
only displays 4 decimals in the result of the calculations, as in the examples above. However,
the precision can be changed by typing format long, which sets the number of digits to 15.
1 >> x
2 x =
3 2.7224
4 >> format l o n g
5 >> x
6 x = 2.722389432263983
To finish o↵ this section, we list a few useful commands.
• clear. This command removes all variables from the workspace. Bear in mind that
the content of the workspace is not deleted between executions. That may cause unpre-
dictable results; therefore, it’s a good idea to start independent calculations by cleaning
the working space.
• clc. This command is used to clear the command window.
• semicolon ; and comma ,. The semicolon symbol is used to enter multiple statements
per line and force MATLAB to remove the output from the command window. The
comma forces the system to display the output. Compare both in the following example.
1 >> x=2; y=3;
2 >>
3 >> x=2, y=3
2.3. Mathematical Functions 11
4 x =
5 2
6 y =
7 3
• Up-arrow ". By pressing the " key, a window with the commands entered earlier on pops
up. It is possible to retrieve those commands from that window and modify them for
your next calculations.
• ctrl+c (Windows) or command+c (Mac). This command interrupts the current compu-
tation.
• help. The syntax of this command is help command. It provides the user with the basic
information about the requested command.
• doc. The command doc command opens the online version of the help manual. This
manual is very well written and plenty of useful examples.
The elementary functions needed for scientific computation are already built into MATLAB.
Table 2.2 shows the most common; for the full list, check the link https://www.mathworks.
com/help/symbolic/mathematical-functions.html.
Along with the elementary functions, MATLAB has a few pre-defined constants, shown
in Table 2.3.
12 Introduction to MATLAB
pi 3.14159265 . . .
i, j Imaginary unit
Inf +1
NaN Not a number
Table 2.3: Pre-defined mathematical constants in MATLAB
Since constants i, j are pre-defined as the imaginary unit, it is advisable to use other
variables for indexing (ii or jj, for example). However, it is possible re-assign the values of
those constants.
1 >> i =3
2 >> i
3 i =
4 3
5 >> i=s q r t ( 1)
6 i =
7 0.000000000000000 + 1.000000000000000 i
Number e is represented by exp(1) in MATLAB.
5 v =
6 4 5 6
If we want to create a column vector, then we have to use a semicolon to separate the
entries.
1 >> w= [ 1 ; 2 ; 3 ]
2 w =
3 1
4 2
5 3
To find the transpose of a matrix, we employ the operator ’.
1 >> w= [ 1 2 3 ]
2 w =
3 1 2 3
4 >> v=w’
5 v =
6 1
7 2
8 3
To enter a n ⇥ n matrix in MATLAB, we begin with a left square bracket [, then we enter
the rows as 1 ⇥ n vectors, we add ; at the end of each row, and we finish o↵ by closing the
matrix with a right square bracket ].
1 >> A= [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
2 A =
3 1 2 3
4 4 5 6
5 7 8 9
Elements from a matrix can be obtained by referencing them by row and column. In the
previous example, A(1,2)=2. The first index is the row and the second is the column. The
indices can be used to change the entries of the matrix.
1 A =
2 1 2 3
3 4 5 6
4 7 8 9
5 >> A( 2 , 2 ) =0; A( 1 , 2 ) =0
6 A =
7 1 0 3
8 4 0 6
9 7 8 9
So far, we have defined matrices by enumeration, that is, by explicitly listing their elements. It
is possible to define matrices by providing formulas or properties describing them. Two easy
ways to do this in MATLAB are the following.
• The operator colon :. This operator allows to build vectors whose entries are equally
spaced. Its syntax is x=a:b:c. It returns a vector starting at a and fills it with entries
a + b, a + 2b, . . . , a + kb until c is reached.
14 Introduction to MATLAB
• The function linspace(a, b,n). It returns a vector of n linearly spaced between a and
b, both included. If the argument n is omitted, then it is assumed to be 100.
1 >> x = 0 : 0 . 1 : 1
2 x =
3 0 0.1000 0.2000 0.3000 0.4000 0.5000
0.6000 0.7000 0.8000 0.9000 1.0000
4 >> y=l i n s p a c e ( 0 , 1 , 1 1 )
5 y =
6 0 0.1000 0.2000 0.3000 0.4000 0.5000
0.6000 0.7000 0.8000 0.9000 1.0000
The colon operator is actually a selection operator and can be used on matrices. For
example,
1 A =
2 1 2 3
3 4 5 6
4 7 8 9
5 >> A( 1 , : ) , A( : , 1 )
6 ans =
7 1 2 3
8 ans =
9 1
10 4
11 7
The colon operator allows us to extract submatrices from a given matrix. Here we extract the
two last columns of A by typing A(:, 2:3). The colon operator in the first argument is telling
MATLAB to consider all rows in A, and then the second argument is limiting the selection to
columns 2 and 3.
1 A =
2 1 2 3
3 4 5 6
4 7 8 9
5 >> A( : , 2 : 3 )
6 ans =
7 2 3
8 5 6
9 8 9
As before, the colon operator can be used to assign new values to rows or columns in a
matrix, or even delete them.
1 A =
2 1 2 3
3 4 5 6
4 7 8 9
5 >> A ( 1 : 2 , : ) =0
6 A =
2.4. Matrices and Matrix Operations 15
7 0 0 0
8 0 0 0
9 7 8 9
10 >> A ( 1 : 2 , : ) = [ ]
11 A =
12 7 8 9
When the colon operator stands alone it refers to all rows and columns. For example,
1 >> A= [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
2
3 A =
4 1 2 3
5 4 5 6
6 7 8 9
7 >> A ( : )
8 ans =
9 1
10 4
11 7
12 2
13 5
14 8
15 3
16 6
17 9
Notice that the operator : starts with a row index and then processes the matrix for all values
of the column for that row; after that, it moves to the next row index, and so on.
To pick up the last row or column of a matrix, we use the keyword end. It retrieves the last
index of the specified dimension.
1 >> A= [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
2 A =
3 1 2 3
4 4 5 6
5 7 8 9
6 >> A( end , : )
7 ans =
8 7 8 9
9 >> A( : , end )
10 ans =
11 3
12 6
13 9
The dimension of a matrix is computed with the command size. Using matrix A again,
we have
1 >> s i z e (A)
2 ans =
16 Introduction to MATLAB
3 3 3
Matrix processing is quite flexible and powerful in MATLAB. The entries of a matrix are not
limited to numbers; they can be more general objects, including matrices themselves.
1 >> B=[1 2 ; 3 4 ]
2 B =
3 1 2
4 3 4
5 >> C=[ 1 2; 3 4]
6 C =
7 1 2
8 3 4
9 >> A=[B C; C B ]
10 A =
11 1 2 1 2
12 3 4 3 4
13 1 2 1 2
14 3 4 3 4
In Table 2.4 a few functions to generate matrices (zero matrices, identity matrices, diagonal
matrices, and the like) are listed.
(1) The matrix composed of the first and first row and the first column
third rows in A
(4) The diagonal matrix of A
(2) The matrix composed of the first and
third columns in A
(5) The matrix obtained from A by substi-
(3) The matrix obtained by removing the tuting the negative numbers for zeros
2.4. Matrices and Matrix Operations 17
Exercise 2.4.2 By using MATLAB commands and functions, for the given the matrices
0 1 0 1
1 2 ! 1 1 0
B C 1 2 3 B C
A = @ 3 4 A, B = ,C=@ 3 2 1 A
4 5 6
5 6 0 1 1
0
find AB, (3 + 2i)A + (2 5i)B, C 3 , det(C), C 1
, the ranks of A and C, the eigenvalues of C,
and the diagonal elements of B and C.
The way MATLAB make plots is again based on matrices. If we want to plot a function
y = f (x) on a certain interval [a, b], we need to provide MATLAB with two vectors, x and y.
The first contains the x-coordinates and the second the y-coordinates. For example, to plot
f (x) = x3 + 1 on the interval [ 1, 1], we use the function plot as in the code below.
1 >> x = 1 : 0 . 1 : 1 ;
2 >> y=x . ˆ 3 + 1 ;
3 >> p l o t ( x , y )
and the resulting figure is below.
MATLAB just joins the pairs (x, y) with line segments. The higher the number of points
in x, the smoother the plotting of the function becomes. Notice that vectors x and y have to
have the same dimension.
Discrete functions can also be plotted in MATLAB. Instead of using the command plot,
we will use the command stem; we’ll add ’k’ to tell MATLAB to draw the function in black.
1 >> x = 1 : 0 . 1 : 1 ;
2 >> y=x . ˆ 3 + 1 ;
3 >> stem ( x , y , ’ k ’ )
2.5. Basic Plotting 19
Figure 2.3 shows the plot of the discrete version of the function y = x3 + 1
MATLAB is plenty of functions to improve the appearance of figures. For example, with
MATLAB, it is possible to change the styles and color of the line segments in the plot, add
legends, control the x- and y-axis values, put text in the figure, or establish the limits the
function will be plotted within.
For the plot lines, there are three attributes MATLAB is able to control, namely, color, line
style, and marker. Table 2.6 shows the values those attributes can take. This table only shows
the basic colors, but it is possible to employ a wider gamut of colors by specifying an RGB
combination; see color specification for lines in https://www.mathworks.com/help/matlab/ref/
line.html?searchHighlight=line&s tid=doc srchtitle.
The finish of Figure 2.4 is neater than that of Figures 2.2 and 2.3, where just the bare plot
was shown with default values for the plot attribute. In Figure 2.4 we notice that a title was
added, the fonts and their sizes were carefully chosen, the values of the function were put near
20 Introduction to MATLAB
the function points, the x and y limits were also specified. Let’s how to instruct MATLAB to
do all this.
Figure below we have the code written to draw Figure 2.4. We will analyze the code to learn
how to create more sophisticated figures in MATLAB. We started o↵ by clearing the working
space with the clear command. Next, we defined two functions (lines 3–6). The vectors to be
plotted are (x1, y1) and (x2, y2).
There will be two sub-figures in one figure. By using the subplot we tell MATLAB how
the sub-figures are going to be organized. subplot(m,n,k) divides the current figure into an
m ⇥ n grid and creates figures in the position specified by k. In our case, we created a 2 ⇥ 1
vertical grid; the first figure is drawn in lines 8–16.
Focusing our attention on the first plot, we explain how we added more elements to it.
The font size can be set as well as the font family (here we used the default one).
• The line style. In this case, we set the color to black, with filled line style, and line width
of 3 (in points).
1 stem ( x1 , y1 , ’ k ’ , ’ f i l l e d ’ , ’ LineWidth ’ , 3 )
2.5. Basic Plotting 21
• The appearance and the spacing of x and y ticks can be controled, as shown in the code
below. gca is a system matrix containing the properties for the current chart.
1 s e t ( gca , ’ XTick ’ , 4 : 1 : 5 , ’ F o n t S i z e ’ , 1 8 , ’ FontName ’ , ’ Times New Roman
’)
2 s e t ( gca , ’ YTick ’ , 0 : 1 : max( y1 ) , ’ F o n t S i z e ’ , 1 8 , ’ FontName ’ , ’ Times New
Roman ’ , ’ box ’ , ’ o f f ’ )
The command box is used to remove the box around the y axis in the figure.
1 %FIGURE 3 . 4
2 clear ;
3 x1 = l i n s p a c e ( 4 ,5 ,10) ;
4 y1 = [ 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 ] ;
5 x2 = l i n s p a c e ( 4 ,5 ,10) ;
6 y2 = [ 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 ] ;
7
8 subplot (2 ,1 ,1)
9 stem ( x1 , y1 , ’ k ’ , ’ f i l l e d ’ , ’ LineWidth ’ , 3 )
10 s e t ( gca , ’ XTick ’ , 4 : 1 : 5 , ’ F o n t S i z e ’ , 1 8 , ’ FontName ’ , ’ Times New Roman ’ )
11 s e t ( gca , ’ YTick ’ , 0 : 1 : max( y1 ) , ’ F o n t S i z e ’ , 1 8 , ’ FontName ’ , ’ Times New
Roman ’ , ’ box ’ , ’ o f f ’ )
12 t e x t ( x1 , y1 +0.3 , s t r i n g ( y1 ) , ’ F o n t S i z e ’ , 1 8 , ’ FontWeight ’ , ’ b o l d ’ )
13 xlim ([ 5 6 ] )
14 ylim ( [ 0 1+max( y1 ) ] )
15 t i t l e ( [ ’ \ f o n t s i z e {16} ( a ) Unit sample s e q u e n c e ’ ] )
16 d a s p e c t ( [ 1 1/2 1 ] )
17
18 subplot (2 ,1 ,2)
19 stem ( x2 , y2 , ’ k ’ , ’ f i l l e d ’ , ’ LineWidth ’ , 3 )
20 s e t ( gca , ’ XTick ’ , 4 : 1 : 5 , ’ F o n t S i z e ’ , 1 8 , ’ FontName ’ , ’ Times New Roman ’ )
21 s e t ( gca , ’ YTick ’ , 0 : 1 : max( y1 ) , ’ F o n t S i z e ’ , 1 8 , ’ FontName ’ , ’ Times New
Roman ’ , ’ box ’ , ’ o f f ’ )
22 t e x t ( x2 , y2 +0.3 , s t r i n g ( y2 ) , ’ F o n t S i z e ’ , 1 8 , ’ FontWeight ’ , ’ b o l d ’ )
23 xlim ([ 5 6 ] )
24 ylim ( [ 0 1+max( y2 ) ] )
25 t i t l e ( [ ’ \ f o n t s i z e {14} ( b ) Unit s t e p s e q u e n c e ’ ] )
26 d a s p e c t ( [ 1 1/2 1 ] )
27 return
• The x and y limits are set by specifying an interval as shown in the lines below.
1 xlim ([ 5 6 ] )
2 ylim ( [ 0 1+max( y1 ) ] )
• Finally, the command daspect(ratio) sets the data aspect ratio for the current axes.
daspect takes a vector of three real numbers as parameter. Each number is the relative
22 Introduction to MATLAB
length of the data units along the three axis, given in the order x-axis, y-axis, and z-axis.
In our code we have daspect([1 1/2 1]) and this means that the length along the x-axis
from 0 to 1is going to be equal to the length of y-axis from 0 to 1/2.
1 d a s p e c t ( [ 1 1/2 1 ] )
Unless MATLAB is told otherwise, figures are drawn on separate windows. If we want to
draw two figure on the same window, we have to use the command hold as shown in the code
below.
1 x1 = 0 : 0 . 1 : 2 ∗ p i ;
2 y1=s i n ( x1 ) ;
3 x2=x1 ;
4 y2=c o s ( x2 ) ;
5 h o l d on
6 p l o t ( x1 , y1 , ’ k +’ )
7 p l o t ( x2 , y2 , ’ b : ∗ ’ )
8 hold o f f
The output is shown in Figure 2.6. The sine function was drawn in black, with solid line
style and a plus sign as marker. The lines in the plot of the cosine function are blue, dotted,
and have an asterisk as marker.
Exporting figures from MATLAB can be done from the figure window (generated when after
a plot or a stem command is issued). Once there, go to File!Export Setup. This window
contains many parameters to control the final output of the figure. In particular, the rendering
method can changed and the file resolution can be set as appropriate; see Figure 2.7
2.6. Introduction to MATLAB Programming 23
Values can be specified in several ways. For example, just as a vector n : k : m, where
n is the initial value, k the step, and m the final value. Values can also be a matrix and
then index runs over the columns the matrix. The script below generates a random 4 ⇥ 3
matrix and displays the maximum of each column; we used the command disp to display
the output on the screen.
1 J=rand ( 4 , 3 )
2 for I = J
3 d i s p ( ’ Current maximum e l em e n t : ’ )
4 d i s p (max( I ) )
5 end
while, continue, break It repeats a block of code while the condition is true. Its syntax is:
2.6. Introduction to MATLAB Programming 25
1 while expression
2 statements
3 end
The command continue is used to pass the control to the next iteration of the while loop.
In the example below, taken from the MATLAB online help (https://www.mathworks.
com/help/matlab/ref/while.html?searchHighlight=while&s tid=doc srchtitle), the script
counts the number of lines without taking into account blank lines and comments. When
a blank line or a comment is found or if the line is not a character array, then continue
ignores the remaining of the script and jumps up to the next iteration. In the code below,
some file handling functions were used; see the online help.
1 f i d = f o p e n ( ’ magic .m’ , ’ r ’ ) ;
2 count = 0 ;
3 while ˜ f e o f ( f i d )
4 line = fgetl ( fid ) ;
5 i f isempty ( l i n e ) | | strncmp ( l i n e , ’%’ , 1 ) | | ˜ i s c h a r ( l i n e )
6 continue
7 end
8 count = count + 1 ;
9 end
10 count
After having introduced all the operators in MATLAB, we provide the reader with a table
that present them in decreasing order of precedence, 1 being the highest precedence. Operators
are evaluated from left to right.
26 Introduction to MATLAB
Precedence Operator
1 Parenthesis ( )
2 Transpose .0 , power .^ , power matrix ^
3 Unary plus +, unary minus , logical negation ⇠
4 Multiplication .⇤, right division . /, left division .\
matrix multiplication ?, matrix right division /,
matrix left division \
5 Addition + and subtraction ´
6 Colon operator :
7 <, >, , , ==, ⇠=
8 Element-wise AND &
9 Element-wise OR |
Table 2.8: Operator precedence in MATLAB
Program 2.7.1 Write a program that takes a linear system of equations and determines
whether the system has no solution, one solution, or infinite solutions. If it has solutions,
it outputs them. The coefficients of the systems are complex numbers. The input can be read
from a file.
Program 2.7.2 Implement the divide-and-conquer sorting algorithm in MATLAB. The input
is a set of n real numbers and the output is the set sorted in increasing order. The algorithm
should actually have O(n log n) complexity.
Program 2.7.4 Below there is some pseudocode for the Gauss algorithm. Write a MATLAB
script that takes a matrix as input and returns the matrix in row echelon form and the rank
of the matrix (obtained from its row echelon form). Look up the details about the Gauss
algorithm in the appropriate sources (your algebra notes, the internet).
2.7. MATLAB Exercises 27