0% found this document useful (0 votes)
9 views

DSP 20 Chapter 2

This document provides an introduction to MATLAB. It discusses MATLAB's graphical interface and using it as a calculator. It also covers basic arithmetic operations, variables, functions, and constants in MATLAB.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

DSP 20 Chapter 2

This document provides an introduction to MATLAB. It discusses MATLAB's graphical interface and using it as a calculator. It also covers basic arithmetic operations, variables, functions, and constants in MATLAB.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Chapter 2

Introduction to MATLAB

2.1 About 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

2.2 A Minimum MATLAB Session

2.2.1 The MATLAB Graphical Interface


A MATLAB session starts by clicking on the program icon and logging in your MATLAB
account. The graphical interface appears as in Figure 2.1 (MATLAB R2019 run on Mac OS
X). In the main MATLAB window we notice several important windows, namely: the menu
area, where we see six main areas, home, plots, apps, editor (selected in the image), publish,
and view; the current directory; the editor area (in the figure we see my code to generate
figures for this book); the content of the current folder; the command window; the help
browser in the form of search bar; and the workspace.

Figure 2.1: The MATLAB graphical interface (2019 version on a Mac)

2.2.2 MATLAB as a Calculator


Once the MATLAB session is opened, our first approach would be to use it as an interactive
calculator. In the command window we can type some expressions at the command prompt
(>>).
1 >> 3∗(2 1)+5/3 exp ( 2 )
2 ans =
3 2.7224
2.2. A Minimum MATLAB Session 9

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

7 Did you mean :


8 >> 3∗ x+1
MATLAB points to the position in the expression where it believes the mistake might be
located. It also suggests a correction.
The basic arithmetic operators are +, , ⇤, /. In Table 2.1 the level of precedence is
established for arithmetic operations and functions. Notice the di↵erence between the two next
expressions, one with the proper parenthesis and the other without them.
10 Introduction to MATLAB

Level of Arithmetic operations


Precedence
1 The contents of all parentheses are evaluated first,
starting from the innermost parentheses
and working outward
2 All exponentials are evaluated,
working from left to right
3 All multiplications and divisions are evaluated,
working from left to right
4 All additions and subtractions are evaluated,
starting from left to right
Table 2.1: Hierarchy of arithmetic operations

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.

• . . . To continue a line type this command.

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

2.3 Mathematical Functions

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.

MATLAG Mathematical MATLAB Mathematical


Function Mathematical Function Mathematical
cos(x) Cosine abs(x) Absolute value
sin(x) Sine sign(x) Signum function
tan(x) Tangent max(x) Maximum value
acos(x) Arc cosine min(x) Minimum value
asin(x) Arc sine ceil(x) Round up
atan(x) Arc tangent floor(x) Round down
exp(x) Exponential round(x) Round to nearest integer
sqrt(x) Square root rem(a, b) Remainder after the division a/b
log(x) Natural logarithm angle(x) Phase angle
log10(x) Common logarithm conj(x) Complex conjugate
Table 2.2: Elementary functions in MATLAB

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.

Exercise 2.3.1 Do the following calculations in the MATLAB command window.

(1) cos(⇡/2) + sin(⇡/2) (5) The conjugate of 1 + i.


2
e + e2 (6) The remainder of the division 5 by 3.
(2)
2
(3) log10 (5) · ln(10) ln(5) (7) The floor, the ceiling, and the round of
3.6 and 3.4
(4) The argument of the complex number p
1+i (8) arcsin( 2/2)

2.4 Matrices and Matrix Operations

2.4.1 Matrix Construction


Matrices are at the core of MATLAB. Almost all data structures in MATLAB are thought
of in terms of matrices, and many algorithms are consequently designed to work on matrices.
This requires a conceptual change in the user’s mentality. Users familiar with other systems,
such as C or C++, may find working with MATLAB somewhat uneasy.
A vector, defined as a matrix of order 1 ⇥ n is entered into MATLAB by just typing its
entries between square brackets (leaving spaces or commas between the entries).
1 >> v =[1 , 2 , 3 ]
2 v =
3 1 2 3
4 >> v=[4 5 6 ]
2.4. Matrices and Matrix Operations 13

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.

eye(m,n) Returns an m-by-n matrix with 1 on the main diagonal


eye(n) Returns an n-by-n square identity matrix
zeros(m,n) Returns an m-by-n matrix of zeros
ones(m,n) Returns an m-by-n matrix of ones
diag(A) Extracts the diagonal of matrix A
rand(m,n) Returns an m-by-n matrix of random numbers
Table 2.4: Matrix generators

Exercise 2.4.1 Given the matrix


0 1
1 2 5
B C
A=@ 0 3 4 A
2 5 3

find in MATLAB the following submatrices.

(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

2.4.2 Matrix Operations and Functions


MATLAB implements all the matrix operations that are normally done in mathematics and
engineering. Let Mn⇥m be the set of matrices of order n ⇥ m. Table 2.5 lists the main matrix
operations and functions in MATLAB.

Input Operation MATLAB


operation/function
A, B 2 Mn⇥m A+B A+B
A 2 Mn⇥m , B 2 Mm⇥k A · B 2 Mn⇥k A*B
A 2 Mn⇥n An An
↵ 2 C, A 2 Mn⇥m ↵·A ↵*A
A 2 Mn⇥n det(A) det(A)
A 2 Mn⇥n rank of A rank(A)
A 2 Mn⇥n A 1 inv(A)
A 2 Mn⇥n Eigenvalues eig(A)
A 2 Mn⇥m Diagonal elements diag(A)
Table 2.5: Matrix operations

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.

2.4.3 Array operations


There are two modes in which MATLAB can operate with matrices. One is the matrix mode,
where operations are carried out on matrices as a whole. The operations defined in the previous
sub-section were matrix operations. The second mode is called array operations. In this mode
the operations are performed element by element on the input matrices. This mode of operation
is also called point-wise operation. For point-wise operations to be well defined the matrices
have to have the same dimension. The point-wise sum and subtraction coincide for both
modes. There are three point-wise operations defined in MATLAB, namely, product, division,
and exponentiation, which are notated, respectively by .*, ./, .^ . If A = (aij ), B = (bij ),
where bij is always non-null, then these operations are defined as

• A. ⇤ B = (a11 · b11 , a12 · b12 , . . . , ann · bnn )

• A./B = (a11 /b11 , a12 /b12 , . . . , ann /bnn )

• A.^ B = (ab1111 , ab1212 , . . . , abnn


nn
)
18 Introduction to MATLAB

• A.^ 2 = (a211 , a212 , . . . , a2nn )


0 0
Exercise 2.4.3 Take the matrices in Exercise 2.4.2 and compute A. ⇤ B , C.^ 3, (A )./B in
MATLAB.

2.5 Basic Plotting

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.

Figure 2.2: Plotting functions in MATLAB

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

Figure 2.3: Plotting functions in MATLAB

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.

Symbol Color Symbol Line style Symbol Marker


k Black - Solid + Plus sign
r Red – Dashed Circle
b Blue : Dotted * Asterisk
g Green -. Dash-dot · Dot
c Cyan none No line ⇥ Cross
m Magenta s Square
y Yellow d Diamond
Table 2.6: List of attributes for the lines of a plot

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 2.4: Plotting Figure 3.4

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.

• Title. Insert a title by using the command


1 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 ’ ] )

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

Figure 2.5: MATLAB code to draw Figure 3.4

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

Figure 2.6: Plotting two functions in the same figure

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

Figure 2.7: Export setup for figures in MATLAB

2.6 Introduction to MATLAB Programming

2.6.1 MATLAB script and functions


There are two ways to program in MATLAB. The first is through MATLAB scripts; the
second is through MATLAB functions. Scripts are just files containing a sequence of MAT-
LAB commands. A script file was the one shown in Figure 2.5, written to produce a figure.
Scripts are conceive to automate the execution of tasks in MATLAB. The language is inter-
preted. MATLAB functions are similar to routines. They can accept arguments and return
an output. The main di↵erence between a script and function is that functions have their own
working space, which is not shared with the base working space. Thus, variable overwriting
and unpredictable behavior is avoided. Both scripts and functions are written to files whose
extension is .m (they are called m-files).
Below there is the code of a MATLAB function that produces a n⇥m-order matrix M = (aij )
whose entries are i·j, for i = 1, . . . , n and j = 1, . . . , m. Line 1 contains the function declaration.
Here M is the output and n, m are the arguments. Lines 2–5 check for the validity of the
arguments. Line 3 means that n has to be a finite numerical value of order 1 ⇥ 1 (that’s what
(1, 1) means). The rest of the code is straightforward.
1 f u n c t i o n M=Matri xGenerator ( n ,m)
2 arguments
3 n ( 1 , 1 ) {mustBeNumeric , mustBeFinite }
4 m ( 1 , 1 ) {mustBeNumeric , mustBeFinite }
5 end
6 M=z e r o s ( n ,m) ;
7 f o r a =1:n
8 f o r b=1:m
9 M( a , b )=a∗b
10 end
11 end
12 end
24 Introduction to MATLAB

2.6.2 MATLAB programming language


In this section we are going to examine the basic control commands in MATLAB.

if, else if, else . The syntax is


1 i f expression
2 statements
3 e l s e i f expression
4 statements
5 else
6 statements
7 end

where expression is to be evaluated. If expression is non-empty and di↵erent from zero


(real or logical), then expression is true. When true, the statements in the if are executed.
Otherwise, if present, MATLAB executes the else or else if blocks.

for . It executes a block of statements a fixed number of times. The syntax is


1 f o r index = values
2 statements
3 end

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

An output given by running this script is:


1 >> FiguresCode2
2 J =
3 0.7094 0.6551 0.9597
4 0.7547 0.1626 0.3404
5 0.2760 0.1190 0.5853
6 0.6797 0.4984 0.2238
7 Current maximum el em en t :
8 0.7547
9 Current maximum el em en t :
10 0.6551
11 Current maximum el em en t :
12 0.9597

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

Table 2.7 summarizes the main control commands in MATLAB.

if, elseif, else Execute statements if condition is true


for for loop to repeat specified number of times
switch, case, otherwise Execute one of several groups of statements
while while loop to repeat when condition is true
continue Pass control to next iteration of for or while loop
break Terminate execution of for or while loop
end Terminate block of code or indicate last array index
pause Stop MATLAB execution temporarily
return Return control to the invoking program
Table 2.7: Main control commands in MATLAB

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

2.7 MATLAB Exercises

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.3 Write a program that, given a Diophatine equation ax + by = c, a, b, c 2 Z,


determines whether the equation has solution and, if it does, find it.

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

Algorithm 2.1 Gauss algorithm


1 h := 1
2 k := 1
3
4 while h  n and k  m
5 imax := argmax(i = h . . . n, abs(A[i, h]))
6 i f A[imax , h] = 0
7 k := k + 1
8 else
9 swap rows(h, imax )
10 for i = h + 1...n:
11 f := A[i, k]/A[h, k]
12 A[i, k] := 0
13 for j = k + 1...m:
14 A[i, j] := A[i, j] A[h, j] ⇤ f
15 h := h + 1
16 k := k + 1

You might also like