1
Introduction to MATLAB1
The aim of this chapter is to make the reader familiar with the programming tool MATLAB. No previous knowledge of MATLAB is assumed, hence the introduction is given in a very analytical way, starting from the very basics. Before starting our tour to the wonderful world of MATLAB let us note some conventions made during the writing of this book:
1. In some cases, a command or a result is written in more than one line. You should consider that the command is written in one line. In the usual case, the result also occupies a single line.
2. There are times that the results of a MATLAB command are given in a slightly different format (e.g., fewer spaces or less decimal digits) from the one that you will see in your computer. This is made to save space.
We are ready to start our introduction to the programming tool MATLAB.
1.1 What Is MATLAB?
MATLAB is a high-level technical computing language equipped with a user-friendly interface. Its name stems from the words MATrix and LABoratory as it is based on the use of matrices. MATLAB is a product of Mathworks, and the first version of MATLAB was released in 1984. It was first adopted by the control engineering and applied math- ematics communities, but as years passed, numerous functions (categorized in toolboxes) were embedded making MATLAB an extremely powerful tool useful for scientists and engineers from various disciplines. For example, MATLAB can be used in a wide range of applications, such as telecommunications, signal and image processing, control, mathemat- ics, financial modeling, bioengineering, aeronautics, and many more. It is also very useful and popular in education because a student can easily derive handy results without facing many difficulties, as the language syntax and structure is very simple and the data analysis and visualization is straightforward. With the help of MATLAB in this book the reader is expected to understand in a comprehensive and practical way the difficult concepts of the signals and systems theory.
1.2 Working Environment
The working environment of MATLAB consists of several windows that are illustrated in Figure 1.1.
1
2
Signals and Systems Laboratory with MATLAB1
Command prompt
User M-files
Current directory
Path browser
Previously executed commands
FIGURE 1.1
The working environment of MATLAB.
. The Command window is the main window of the program. The commands are typed at the command prompt and the obtained results also appear in the com- mand window.
. In the Command History window one can see all the previously executed commands.
. Moreover, at the lower left part of the figure we notice the Current Directory. The current directory specifies the active folder of MATLAB. By default the current directory is the folder work.
There are two possible ways to work with MATLAB. The first is through the command window where the user types and executes the commands one by one, while the second option is to write a sequence of commands in the text editor, i.e., to formulate a program and execute the commands in a batch mode. This kind of programs are known as scripts, and are just like any other program written in another programming language. A script file is executed either directly from the editor window from the menu Debug!Run or by typing the script’s name at the command prompt. In any case, the script file must be saved in the Current Directory. The extension of this file type is .m, and this is why scripts (together with functions) are sometimes called M-Files.
1.3 Getting Started
In this section, we illustrate how to perform some basic operations on MATLAB. The presentation is done in the form of tables. In the left part we give the MATLAB command, in the middle we present the result of the executed command, while at the right part the command and the corresponding results are explained.
Introduction to MATLAB1 3 1.3.1 Simple Arithmetic Operations
The four operators þ, “, *, and=are used as usual to add, subtract, multiply, and divide two numbers. In MATLAB a left division operatornis also available, and the power of a number is computed by the operator ^.
Commands Results
3þ5 ans 1⁄4 8 5″2 ans 1⁄4 3 6*7 ans 1⁄4 42 2=4 ans 1⁄4 0.5 2n4 ans 1⁄4 2 2^3 ans 1⁄4 8
Comments
% Addition
% Subtraction
% Multiplication % Division
% Left division % Power
1.3.2 Comments
Notice the symbol %. The symbol % is used to insert comments. Anything written to the right of % is considered comment and is not taken into account from MATLAB.
1.3.3 The Variable ans
The symbol ans is a variable. By default, the result of the last executed MATLAB command is assigned to the variable ans. To see the value which is stored in ans, simply type the word ans at the command prompt.
Commands
ans ans1⁄43
Results
ans 1⁄4 8 ans 1⁄4 3
Comments
The result of the most recently executed command is assigned to the variable ans.
Additionally, a value can be assigned directly to ans.
Remark
In order to recall a previously executed command you can press the up-arrow key of your keyboard.
1.3.4 Priority of Operations
Multiple operations can be performed in a single statement. The priority in which the operations are executed is common to the one used in all programming languages: power, multiplication-division, addition-subtraction. Also, the parentheses are used in the usual way.
4
Signals and Systems Laboratory with MATLAB1
Commands
3þ7*2 2^2þ2*(3″2*(1þ14=7))
Results
ans 1⁄4 17 ans 1⁄4 “2
Comments
The multiplication is executed before the addition. The priority is specified from the parentheses.
A decimal number is defined by employing the dot operator. If the integer part is zero it can be omitted for briefness. A negative number is defined by writing the minus sign before the number.
Commands
0.4 þ 1.2 .2 þ.4 “3”1
Results
ans 1⁄4 1.6000 ans 1⁄4 0.6000 ans 1⁄4 “4
Comments
Operations between decimal numbers.
If the integer part of a decimal number is zero it is possible to omit it.
Operations between negative numbers.
A useful format of writing a number is to express it as a power of ten. This format is often called scientific. The short way of writing a number x in the form y*10n is as follows.
Commands Results
1e3 ans 1⁄4 1000
3e1 ans 1⁄4 30
4e”2 ans 1⁄4 0.0400
36e9 ans 1⁄4 3.6000e þ 10
1.3.5 Constants
Comments
1*103.
3*101.
4*10″2.
36*109. The result is written as 3:6*1010.
In MATLAB there are also constants. Some of them are presented in the table below.
Commands Results
pi ans 1⁄4 3.1416
i ans 1⁄4 0 þ 1.0000i
j ans 1⁄4 0 þ 1.0000i
inf ans 1⁄4 Inf “inf ans 1⁄4 “Inf
eps ans 1⁄4 2.2204e ” 016
NaN ans 1⁄4 NaN
realmax ans 1⁄4 1.7977e+308 realmin ans 1⁄4 2.2251e ” 308
Comments
Mathematical constant p.
Imaginary unit i (used to define complex numbers).
Alternative representation of the imaginary unit.
Infinity (1).
Minus infinity (“1).
Spacing of floating point numbers. This is the highest accur- acy in which the result of an operation can be calculated.
Unidentified number (not a number).
Largest positive floating point number defined in MATLAB. Smallest positive floating point number defined in MATLAB.
Introduction to MATLAB1 5 1.3.6 Built-In Functions
There are many built-in functions available in MATLAB. Some of them are presented below.
Commands
sqrt(2) abs(“4)
sign(3)
exp(1) log(1) log10(100) log2(4) sin(pi=2) cos(pi) tan(pi=4) asin(0.5) acos(“1) atan(1) sinh(0.1) cosh(0.2) tanh(pi=6) ceil(0.6) floor(0.6) round(0.6) fix(0.6) factorial(5)
Remark
Results
ans 1⁄4 1.4142 ans1⁄44
ans1⁄41
ans 1⁄4 2.7183
ans1⁄40
ans 1⁄4 2 ans1⁄42 ans1⁄41 ans1⁄4″1 ans1⁄41
ans 1⁄4 0.5236 ans 1⁄4 3.1416 ans 1⁄4 0.7854 ans 1⁄4 0.1002 ans 1⁄4 1.0201 ans 1⁄4 0.4805 ans 1⁄4 1
ans 1⁄4 0 ans 1⁄4 1 ans 1⁄4 0 ans 1⁄4 120
Comments
Square root.
Absolute value.
The function sign returns 1 if the input number is positive, 0 if the input is zero, and “1 if the input is negative.
Exponential.
Natural logarithm.
Base 10 logarithm.
Base 2 logarithm.
Sine.
Cosine.
Tangent.
Arcsine (inverse sine).
Arccosine (inverse cosine).
Arctangent (inverse tangent).
Hyperbolic sine.
Hyperbolic cosine.
Hyperbolic tangent.
Rounding toward the closer larger integer. Rounding toward the closer smaller integer. Rounding toward the closer integer. Rounding toward the closer-to-zero integer. Factorial function.
The input argument of a trigonometric function must be in radians. To convert degrees to radians we multiply degrees by p=180.
Example
Compute the cosine of 608.
In order to not get confused, an easy way is to use the proportion method:
180 p)x1⁄460p: 60x 180
6
Signals and Systems Laboratory with MATLAB1
Hence,
1.3.7 Variables
Commands
cos(60*pi=180)
Results Comments
ans 1⁄4 0.5000 Cosine of 608
At MATLAB there is no need to declare the variables before assigning them a value. A variable can have any name as long as it does not start with a number and it does not include spaces or special characters. Finally, there is a distinction between capital and small letters.
Example
Compute the expressions
. .
sin (45)2 þ cos (45)2 sin (45) % cos (45)
Commands
theta 1⁄4 45*pi=180 a 1⁄4 sin(theta)
b 1⁄4 cos(theta) c1⁄4a^2þb^2
a*b
d 1⁄4 cþans
A1⁄46 a1⁄43
c 1⁄4 Aþa
Results
theta 1⁄4 0.7854 a 1⁄4 0.7071
b 1⁄4 0.7071 c 1⁄4 1
ans 1⁄4 0.5000 d 1⁄4 1.5000
A1⁄46 a1⁄43
c 1⁄4 9
Comments
First, we convert the 458 to radians. The result is assigned to a variable named theta.
Definition of the variable a.
Definition of the variable b.
The result of the first expression is assigned to the variable c.
The second expression is computed and the result is stored in the default variable ans.
The variable ans can be used for further computations.
Definition of the variable A.
Definition of the variable a.
It is obvious that there is distinction between small and capital letters.
Sometimes it is tedious to have all results displayed. In order to not display a result, we can type a question mark ‘‘;’’ after the command.
Commands
Results
Comments
Nothing is displayed at the command window. This of course does not mean that the command is not executed.
To see the result simply type the variable to which it is assigned.
d1⁄4Aþa;
d d1⁄49
Introduction to MATLAB1 7 Finally we mention that text can be also assigned to a variable. The text is inserted between
single quotes.
1.3.8 Format
Commands Results Comments
x 1⁄4 ‘hello’ x 1⁄4 hello Text assignment to a variable.
The option of specifying the number of decimal digits that are displayed is available in MATLAB. Also, there are other options to set the output format. By default, four decimal digits are displayed, and there are blank lines between the command the variable and the result. By executing the command format we return to the default appearance. The possible formats are illustrated below using p.
Commands
Results
ans 1⁄4 3.1416 ans 1⁄4 3.1416
ans 1⁄4 3.1416 ans 1⁄4 3.1416
ans 1⁄4 3.14159265358979 ans 1⁄4 3.1416eþ000
ans 1⁄4 3.141592653589793eþ000 ans 1⁄4 3.14
Comments
Default format, i.e., 4 decimal digits and blank horizontal lines.
Suppression of blank lines.
Blank lines are inserted between the commands the variable and the result.
Format with 4 decimal digits.
Format with 14 decimal digits.
Format with 4 decimal digits and the number expressed as power of 10.
Format with 14 decimal digits and the number expressed as power of 10.
format pi
format pi
format pi
format pi
format pi
format pi
format pi
format pi
1.3.9 Help in MATLAB
help-lookfor-what-which
format a1⁄41
compact
loose
short long short e
long e
bank hex
Format with 2 decimal digits. Hexadecimal format.
a 1⁄4 3ff0000000000000
In this book we use compact format in order to save space.
A complete manual of the MATLAB commands is offered through the command prompt (also available as an html help file). The command help in MATLAB is the counterpart of command man in Linux. Typing help and the name of the command displays a short
8 Signals and Systems Laboratory with MATLAB1
explanation of how the command is used, available syntaxes, examples, and similar commands. If one types only help, all the available MATLAB commands (divided in categories) with a short description are displayed in the command window.
Commands
help cos
help plot
Results
COS Cosine. COS(X) is the cosine
of the elements of X.
Overloaded methods help sym=cos.m
PLOT Linear plot.
PLOT(X,Y) plots vector Y versus
vector X. If X or Y is a matrix,
then the vector… …….. ….. See also SEMILOGX, SEMILOGY . . . . . . .
Comments
Help about the command cos.
Help about the command plot. Notice that similar commands are also displayed.
Some other related commands are
Commands
look for text what folder which name
Comments
Returns all commands and functions where the word ‘‘text’’ exists. Returns all the files that are in the directory ‘‘folder’’.
Returns the directory in which the file with filename ‘‘name’’ is.
1.4 Memory Management
The variables are saved in a memory region named workspace. To view the saved variables the command workspace is used. Alternatively, one may use the commands who and whos.
Introduction to MATLAB1
9
Commands
workspace
who
whos
Results
Comments
The workspace window is displayed. Inside the window the assigned variables are shown. Editing an existing variable is possible through the workspace.
The assigned variables.
The assigned variables and their size and type.
Your variables are: a
Name Size a 1×1 alpha 1×101
b 1×1
c 1×1
s 1×5
Grand total is 109 elements using 842 bytes
1.4.1 Commands save-load-exit-quit
alpha b
c
s
Bytes
8 double array 808 double array 8 double array 8 double array 10 char array
Assigned variables stay in memory while MATLAB is running. If we close and reopen it the variables are lost. We can use the command save in order to store permanently the assigned variables. The saved variables can be retrieved back to the memory by typing the command load.
Class
Commands
save variables
exit % or quit
We open MATLAB.
load variables
Comments
The workspace variables are saved in a file named variables.mat. If the save command is executed without specifying an output file the variables are saved in a file named matlab.mat. The variables.mat file is saved in the working directory.
The commands exit and quit terminate MATLAB.
The variables that are saved in the file variables.mat are loaded in MATLAB and can be used now.
10 Signals and Systems Laboratory with MATLAB1 1.4.2 The Command clear
The command clear is employed in order to delete a variable from the memory. The syntax is clear and the variable(s) name(s).
Remark
If the command clear is executed without specifying the variable to be deleted, all workplace variables are deleted. The command clear (or clear all) should be used to clear the memory before executing large programs.
Commands
a1⁄45 clear a
a
clear who
Results
a 1⁄4 5.00
??? Undefined function
or variable ‘a’.
Comments
Assign a value to variable a. Deleting variable a from memory.
Indeed variable a is not defined. Deleting all variables from the memory.
Indeed the memory is null.
1.5 Commands diary and clc
Sometimes it is necessary to store the commands and whatever else is displayed in the command window. The command diary is employed to achieve that. Typing diary on anything that is displayed in the command window is recorded in a file named diary.dia. The diary.dia file is saved in the working directory. Typing diary off stops the recording process.
Commands
diary memoir.dia A 1⁄4 5
B 1⁄4 6; diary off
Comments
The file memoir.dia is created. Commands are recorded in the
file memoir.dia.
Stop of the record process.
The command clc (named after the initial letters of clear command) clears the command window from anything written before. It must not be confused with the command clear as it does not delete anything from the memory.
Introduction to MATLAB1 11
1.6 Vectors
MATLAB (named after MATrix LABoratory) is a programming tool specialized for work- ing with matrices (or arrays). Even the scalars are considered as matrices of size 1 & 1. In this section, we introduce a special case of matrices, the vectors.
1.6.1 Row Vectors
To define a row vector, the elements of the vector are given into square brackets […]. Spaces or commas are inserted between the elements. A vector element is specified by its index. The index numbering starts from 1, namely, the index of the first element of a vector is 1. In order to refer to a position in a vector, parentheses are used.
Commands
a 1⁄4 [1 2 3 4 5]
b 1⁄4 [“6,”7,”8,”9,”10]
c 1⁄4 [0.3, 8.5, 6, “2.4] b(3)
b(6)
Results
a1⁄412345 b 1⁄4 “6 “7 “8
Comments
Row vector a of 5 elements.
Row vector b of 5 negative elements.
Row vector c of 4 decimal elements. The third element of vector b.
Vector b has 5 elements. Thus, referring to its 6th position causes an error.
1.6.2 Commands length=size
“9 “10
c 1⁄4 0.30 8.50
“2.40 ans 1⁄4 “8
6.00
??? Index exceeds matrix dimensions.
In order to compute the number of elements of a vector, the appropriate command is the command length. A similar command is the command size. Command size is usually employed to compute the dimensions of a matrix. However, vectors are special case of matrices; thus, using the command size to compute the length of a vector is completely valid.
Commands
length(a)
size(a)
Results
ans 1⁄4 5 ans 1⁄4 1 5
Comments
Number of elements of vector a.
Vector a consists of 1 row and 5 columns.
It is also possible to edit only one specific element of a vector by referring to the position (index) of the vector. If between the position and the rest vector elements there are no defined elements, the null positions are filled with zeros.
12
Signals and Systems Laboratory with MATLAB1
Commands
Results
Comments
5 Vector a is already defined.
The value 99 is inserted at the third position
of vector a, replacing the previous value.
The value 23 is inserted at the tenth position of a. Notice that the intermediate (6th, 7th, 8th, and 9th) positions are filled with zeros.
This way of defining row vectors is quite hard and inappropriate for large-size vectors. In case that the vector elements are equally spaced a vector is defined by giving the first element, the step, that is, the distance between two consecutive elements and the last element separated by the colon operator ‘‘:’’. In other words, a vector with equally spaced elements is defined using the syntax a1⁄4First element:Step:Last element. If the step is 1, it can be omitted. The step can be negative, decimal, or even irrational number. Furthermore, if a vector
a 1⁄4 1
a 1⁄4 1 2 99 4 5
a
a(3)1⁄499 a1⁄41 2 99 4 5
a(10) 1⁄4 23 0 0 0 0 23
2 3 4
is defined in this way the Commands
use of square brackets is not necessary.
Results
3 5 7 9 11
23456
0.2 0.4 0.6 0.8 1.0
210″1″2″3 0.5236 1.0472 1.5708
1.6.3 Addition=Subtraction
a1⁄41:2:11 b1⁄41:6
c 1⁄4 0:0.2:1 d 1⁄4 3:”1:”3
e 1⁄4 0:pi=6:pi
a1⁄41 b1⁄41
c1⁄40
d1⁄43
Comments
The elements of vector a start from 1, end at 11, and are spaced by 2.
If no step is specified, by default the step considered is 1.
Decimal step.
Negative step.
Vector e is defined from 0 to p with step p=6.
e1⁄40
2.0944 2.6180 3.1416
Operations between vectors are usually performed between the corresponding vector elements, i.e., they are operations per element. A necessary condition for the operation between two vectors is that the vectors must be of same size.
. Suppose that a1⁄4[a1a2…an] and b1⁄4[b1b2…bn]. Then, aþb1⁄4[a1 þb1
a2 þb2…an þbn]anda”b1⁄4[a1 “b1
a2 “b2…an “bn].
Comments
Commands
add 1⁄4 aþb sub1⁄4a”b
add 1⁄4 2 sub 1⁄4 0
Results
5 8 11 14 1 2 3 4
17
Vector add is the sum of vectors a and b. Subtraction of vectors.
5
Introduction to MATLAB1 13 1.6.4 Multiplication, Division, and Power
For this type of operations, attention must be paid to the fact that this is an element per element operation. To perform multiplication and division between two vectors or to compute the power of a vector the dot operator ‘‘.’’ has to be inserted before the operator.
. Suppose that a 1⁄4 [a1 a2 …an] and b 1⁄4 [b1 b2 …bn]. Then
a:*b 1⁄4 [a1b1 a2b2 . . . anbn] a:=b 1⁄4 [a1=b1 a2=b2 . . . an=bn] a:nb 1⁄4 [a1nb1 a2nb2 . . . annbn]
a:^k 1⁄4 !ak1 ak2 …akn”, k:^a 1⁄4 1⁄2ka1 ka2 …kan,
a:^b 1⁄4 hab1 ab2 …abni 12n
Commands Results
a a1⁄41 3 5 7 9 11
b b1⁄4123456
where k is a number where k is a number
a.*b ans 1⁄4 a.=b ans 1⁄4
1615284566
1.00 1.50 1.66 1.75 1.80 1.83
Comments
Vectors a and b.
Multiplication element per element. Division element per element.
Left division element per element.
Each element of a is raised to the power of 2.
2 is raised to each element of a.
Each element of a is raised to the power of the corresponding element of b.
a.nb ans 1⁄4 a.^2 ans 1⁄4 1
2.^a ans 1⁄4 2 a.^b ans 1⁄4 1
Commands
a 1⁄4 0:pi=2:2*pi b1⁄43*a
c 1⁄4 cos(a)
Results
a 1⁄4 0 1.5708 3.1416 4.7124 6.2832
b 1⁄4 0 4.7124 9.4248
Comments
Vector a from 0 to 2p with step p=2. In other words, a 1⁄4 [0 p=2 3p=2 2p].
Multiplication between a number and a vector. The dot operator is not used.
Applying the built-in function cos at vector a yields a vector c with elements c 1⁄4 [cos(0) cos(p=2) cos(p) cos(3p=2) cos(2p)].
1.0000 0.6667 0.6000 0.5714 0.5556 0.5455
9254981121
8 32 128 512 2048
9 125 2401 59049 1771561
In case that a vector is multiplied or divided by a number, the use of dot operator is not necessary. The majority of the built-in MATLAB functions can be applied to vectors. The result is a vector of the same size in which the function is applied to each element.
14.1372
c 1⁄4 1.0000 0.0000
18.8496
0.0000
1.0000
“1.0000
14 Signals and Systems Laboratory with MATLAB1 1.6.5 Column Vectors
So far the vectors considered were row vectors. The way to define a column vector is quite similar. In this case, the elements are also inserted between square brackets. However, the elements are not separated by comma but by a question mark ‘‘;’’. A second way to define a column vector is given now: After opening the square bracket and inserting the first element pressing the Enter key moves us to the next line where the second element is inserted. This process continues for all vector elements. Closing the square brackets and pressing Enter provides us a column vector. A third way is to define a row vector and append the apostrophe (or transpose operator)‘‘0’’. The transpose operator transposes the vector, i.e., converts the rows into columns and the columns into rows.
Commands
a1⁄4[1;2;3;4] a1⁄412 3
4
b1⁄4[5 b 1⁄45 66 77 8] 8
Results
10 11 12
Comments
First way of creating a column vector. The question mark is used to change row.
Second way of creating a column vector. By pressing Enter when the square brackets are open also changes row.
Third way of creating a column vector. The transpose operator is used to convert a row vector into a column vector.
The transpose operator also converts a column vector into a row vector.
Column vector z from 1 to 100 with step 0.1.
Indeed z is a an array (or matrix) of 991 rows and
1 column.
The length command in a column vector returns the number of elements.
c1⁄4[9 10 11 12] d1⁄4c’
e1⁄4d’
z 1⁄4 [1:0.1:100]’; size(z)
c1⁄49 d1⁄49
10 11 12
e1⁄49 10 11 12 ans 1⁄4 991 1
ans 1⁄4 991 1.6.6 Dot Product of Two Vectors
length(z)
In order to compute the dot product of two vectors, the vectors must be of the same size. Suppose that a 1⁄4 [a1 a2 …an] and b 1⁄4 [b1 b2 …bn]. The dot product of the vectors a,b is given by
Xn i1⁄41
The dot product of two vectors is a scalar. There are three ways to compute the dot product of two row vectors a and b.
ab 1⁄4
aibi: (1:1)
Introduction to MATLAB1 15
1. The command dot(a,b) directly computes the dot product of the vectors a and b.
2. The dot product can be computed according to its definition, that is, can be computed as sum(a.*b). If the command sum is applied to a vector it returns the sum of the vector elements.
3. A third way based on the multiplication between two matrices is presented in Section 1.7.4.1.
Commands
a1⁄41:4 b1⁄42:5
dot1 1⁄4 dot(a,b) dot21⁄4sum(a.*b)
1.6.7 Useful Commands
Results
a1⁄41 2 3 4 b1⁄42 3 4 5
dot1 1⁄4 40 dot21⁄4 40
Comments
Definition of the row vectors a and b.
Dot product computed by the command dot.
The dot product is computed according to its definition. Notice that the use of the dot operator before the multiplication is necessary.
sum-cumsum-prod-diff-max-min-sort-mean-median
In this section, we introduce various useful (when working with vectors) commands. As already discussed, the command sum returns the sum of the elements of a vector. The command cumsum returns a vector whose elements are the cumulative sum of the previous elements. The command prod is the product of the vector elements, while the command diff returns a vector in which each element is given by its subtraction with the previous element. The commands max and min return the largest and smallest elements of the vector, respectively, as well as their index. The command sort sorts the vector elements in ascending (by default) or descending order. The command mean computes the mean value, while the command median returns the median value. All these commands are suitable also for matrices by slightly changing their syntax.
Commands
a1⁄4[4 2 7 0 6] s 1⁄4 sum(a)
c1⁄4cumsum(a) p1⁄4 prod(a) d1⁄4 diff(a)
[m,i] 1⁄4 max(a) [m,i] 1⁄4 min(a)
max(a)
mean(a) median(a) sort(a) sort(a,’descend’)
Results
a1⁄442706 s 1⁄4 19
Comments
Definition of vector a.
Sum of the elements of a.
Cumulative sum. The result is obtained as [4, 4þ2, 4þ2þ7, 4þ2þ7þ0, 4þ2þ7þ0þ6].
Product of all elements.
Difference between two consecutive
elements, i.e., d(1) 1⁄4 a(2) ” a(1), etc.
The largest value is assigned to variable m,
and its index is assigned to variable i.
The smaller value is assigned to variable m,
and its index is assigned to variable i.
If no output variable is specified, only the
largest value is returned. Mean value of the elements. Median value of the vector. Sorting in ascending order. Sorting in descending order.
c 1⁄4 4
p1⁄40
d 1⁄4 “2
m1⁄47 i1⁄43
m1⁄40 i1⁄44
6 13
13 19
5 “7 6
ans1⁄47
ans 1⁄4 3.8000
ans1⁄44 ans1⁄402467 ans1⁄47 6 4 2 0
16 Signals and Systems Laboratory with MATLAB1
1.7 Matrices
In this section, we introduce how a matrix (or array) is defined in MATLAB. The use of square brackets is necessary. The first way is to type the elements of the first row separated by comas or spaces and then insert a question mark (which corresponds in changing a row), type the elements of the second row, and so on. A second way is to type the elements of the first row, then press Enter to move to the second row, etc. Finally, a third way appropriate for matrices whose elements in each row are equally spaced is to consider a matrix row as a row vector, i.e., to create each matrix row using the syntax First element:Step:Last element and change row by inserting a question mark after the last element of every row.
Commands
A 1⁄4 [1 2 3; 4 5 6; 7 8, 9]
Results
A1⁄41 23 4 56 7 89
Comments
The matrix A is created. It con- sists of three rows and three columns.
Second way of creating a matrix.
Third way of cre- ating a matrix.
A1⁄41 23 456 456
A 1⁄4 [1 2 3 7, 8, 9]
D 1⁄4 [0:.1:.5; 0:”.1:”.5; 0:pi=5:pi]
789
D1⁄40 0.1 0.2 0.3 0.4 0.5
0 “0.1 “0.2 “0.3 “0.4 “0.50 0 0.63 1.26 1.88 2.51 3.14
The elements of a matrix are indexed using two indices. The first index specifies the row and the second index specifies the column. To refer to a matrix position parentheses are used. The matrix dimensions are computed by the command size.
Commands Results
A(1,1) ans 1⁄4 1 A(3,2) ans 1⁄4 8 size(A) ans 1⁄4 3 3
Comments
The first element of matrix A (first row-first column). The element in the third row-second column of A. The dimensions of matrix A (3 & 3).
The majority of the built-in MATLAB functions can be also applied to matrices. The result is a matrix of the same size in which the function is applied to the matrix elements.
Commands
A 1⁄4 [0 pi=2; pi 3*pi=2] B 1⁄4 cos(A)
Results
A 1⁄4 0 1.5708 3.1416 4.7124
B 1⁄4 1.0000 0.0000 “1.0000 “0.0000
Comments A1⁄4 0 p=2!
p 3p=2
B 1⁄4 cos (0) cos (p=2) ! cos (p) cos (3p=2)
Introduction to MATLAB1 17 1.7.1 Matrix Concatenation
Two matrices A and B that have the same number or rows can be concatenated in order to create a new matrix C with the same number of rows. The number of columns of C is the sum of the number of columns of A and B. This process is named matrix concatenation and is applied by typing [A B] or [A,B].
Commands Results
A1⁄4123 A 1⁄4 [1 2 3; 4 5 6; 7 8 9] 456 789
Comments Matrix A of size 3 & 3.
B1⁄411 B 1⁄4 [1 1; 2 2; 3 3] 22 33
C1⁄41 2 C 1⁄4 [A B] 4 5 7 8
3 6 9
Matrix B of size 3 & 2.
Matrix concatenation. A new matrix C is
[m,n] 1⁄4 size(C)
Remark
m1⁄43 n1⁄45
The dimensions of matrix C are 3 rows and 5 columns.
1 1
2 2
3 3 bothAandB.
created that includes the elements of
The process of concatenating matrices is a very useful process. The importance of this process will become clear in Section 1.8.10 where we will learn how to define and plot piecewise functions.
Two matrices A and B that have the same number or columns can be also concatenated if the second matrix B is placed below A in order to create a new matrix C with the same number of columns. The number of rows of C is the sum of the number of rows of A and B. The statement used in this case is [A; B].
Commands
A 1⁄4 [1 2 3; 4 5 6; 7 8 9] B 1⁄4 [1 1 1; 2 2 2]
C 1⁄4 [A;B]
[m,n] 1⁄4 size(C)
1.7.2 Working with Matrices
Results Comments
A1⁄4123
456 MatrixAofsize3&3. 789
B1⁄4111 MatrixBofsize2&3. 222
C1⁄4123
456 Matrix concatenation. A new matrix C is 789 created that includes the elements of 111 both A and B.
222
m1⁄45 The dimensions of matrix C are 5 rows n 1⁄4 3 and 3 columns.
The way of referring to one element of a matrix was introduced earlier. Additionally, it is possible to refer in rows, columns, or sub-matrices. This is achieved by employing the colon
18 Signals and Systems Laboratory with MATLAB1
operator ‘‘:’’ For example, the statement that returns the kth row of A is A(k,:). Similarly, the statement that returns the mth column of A is A(:,m). A sub-matrix from the k1 row to the k2 row and from the m1 column to the m2 column of A is derived by typing A(k1:k2, m1:m2). Finally, the statement A(:) converts matrix A into a column vector.
Commands Results
A1⁄4123 A 1⁄4 [1 2 3; 4 5 6; 7 8 9] 456 789
ans 1⁄4 1 2 3 A(:,:) 4 5 6 7 8 9
A(2,:) ans 1⁄4 4 5 6
ans 1⁄4 3 A(:,3) 6 9
Comments MatrixAofsize3&3.
The whole matrix A.
Explanation: The operator ‘‘:’’ means that all rows and
all columns are selected.
The second row of A.
Explanation: From the rows only the second one is
picked. From the columns all of them are selected.
The third column of A.
Explanation: All rows are selected, while only the third
column is chosen.
The sub-matrix consists of the first two rows and columns of A.
Explanation: From the rows we select from the 1st to the 2nd using step 1. Thus, the 1st and 2nd rows are selected. Similarly, only the first two columns are chosen.
The sub-matrix contains the first and the third rows and columns of A.
Explanation: From the rows we pick from the 1st to the 3rd using step 2. Thus, the 1st and 3rd rows are selected. Similarly for the columns.
The sub-matrix contains the first and the third rows and the first and second columns of A.
Explanation: From the rows we pick from the 1st to the 3rd using step 2. Thus, the 1st and 3rd rows are selected. From the columns we pick from the 1st to the 2nd using step 1. Thus, the 1st and 2nd columns are selected.
The sub-matrix contains the first and the third rows of A.
Explanation: From the rows we pick from the 1st to the 3rd using step 2. Thus, the 1st and 3rd rows are selected. Using the colon operator ‘‘:’’ all columns are selected.
The statement A(:) returns the matrix A as a column vector. The elements are sorted by column.
A(1:2,1:2)
ans1⁄41 2 4 5
ans1⁄41 3 A(1:2:3,1:2:3) 7 9
A(1:2:3,1:2)
A(1:2:3,:)
ans1⁄41 2 7 8
ans1⁄41 2 3 7 8 9
ans 1⁄4 14
7
2 A(:) 5 8 3 6 9
Introduction to MATLAB1 19 1.7.3 Addition=Subtraction
The basic operations in matrices are performed very easily. Suppose that A and B are matrices of size M & N (i.e., they have M rows and N columns) and let the elements of A and B be denoted by aij and bij, i 1⁄4 1,2,…,M, j 1⁄4 1,2,…,N, respectively. The sum AþB is a new matrix C of size M & N and elements cij given by cij 1⁄4 aij þ bij. Similarly, the subtraction A ” B results in a new matrix D of size M & N and elements dij given by dij 1⁄4 aij ” bij.
Commands
A 1⁄4 [1 2 3;4 5 6; 7 8 9] B 1⁄4 [1 1 1; 3 3 3; 5 5 5]
C1⁄4AþB D 1⁄4 A”B
1.7.4 Multiplication of Matrices
Results
A1⁄4123 456 7 8 9 B 1⁄4 1 1 1 333 555
C1⁄4234 7 8 9
12 13 14
D1⁄4012 1 2 3 234
Comments
Matrices A and B of size 3&3. Matrix addition.
Matrix subtraction.
The necessary condition for the multiplication between two matrices is that the number of columns of the first matrix must be equal to the number of rows of the second matrix. The result is a matrix that has the same number of rows with the first matrix and the same number of columns with the second one. Suppose that matrix A has M rows and N columns and matrix B has N rows and K columns. Then matrix C1⁄4A%B has M rows and K columns. The mathematical expression is
(M & N) % (N & K) 1⁄4 (M & K): (1:2)
Let aij,i 1⁄4 1,2,…,M,j 1⁄4 1,2,…,N and bij,i 1⁄4 1,2,…,N,j 1⁄4 1,2,…,K denote the elem- ents of A and B, respectively. The matrix C given by the product A % B is of size (M & K) and its elements are computed by
XN p1⁄41
cij 1⁄4
aipbpj, i 1⁄4 1,2,…,M, j 1⁄4 1,2,…,K: (1:3)
20
Signals and Systems Laboratory with MATLAB1
Commands
A 1⁄4 [1 2 3; 4 5 6]
B 1⁄4 [1 1 1 1;2 2 2 2;3 3 3 3]
C1⁄4A*B D 1⁄4 B*A
Results
A1⁄4123 4 5 6
B 1⁄4 1 1 1 1 2222 3333
C1⁄414 14 14 32 32 32
14 32
Comments
Matrix A is of size 2&3, while
matrix B is of size 3 & 4. Matrix C is the product A%B
and its size is 2&4.
The product B % A is not a valid operation as it does not fulfill condition (1.2).
??? Error using ) * Inner matrix dimensions must agree.
Although the commutative property stands in matrix addition, namely, A þ B 1⁄4 B þ A, when two matrices are multiplied the commutative property is not applicable, i.e., A % B 61⁄4 B % A.
Commands
A 1⁄4 [1 2 3; 4 5 6; 7 8 9]; B 1⁄4 [3 2 1; 6 5 4; 9 8 7];
A*B
Results
ans 1⁄4 42 36 30 96 81 66
150 126 102 ans1⁄418 24 30
Comments
Matrices A and B of size 3&3.
The product A%B.
B%A is not equal to A%B.
B*A 54 90
69 84 114 138
Matrix multiplication must not be confused with the multiplication between vectors. Recall that vector multiplication is an element per element operation and is implemented by inserting the dot operator before the multiplication operator. Multiplication per element can be performed between two matrices A and B, if they are of same size.
Commands
A 1⁄4 [1 2 3; 4 5 6; 7 8 9]; B 1⁄4 [3 2 1; 6 5 4; 9 8 7];
A*B
A.*B
ans 1⁄4 ans 1⁄4
Results
42 36 96 81 150 126
3 4 24 25 63 64
30 66
102
Comments Matrices A and B of size 3&3.
The product A%B.
The element per element multiplication
is implemented using the dot operator. The two results are different.
3 24 63
Introduction to MATLAB1 21 1.7.4.1 The Dot Product as a Special Case of Matrix Multiplication
The dot product was defined in Section 1.6.6. In this section, we present an alternative way of computing the dot product between two row vectors a and b based on matrix multipli- cation. Let N denote the number of elements of each vector. If row vector a is considered as matrix its size is 1 & N. Suppose now that vector b is converted into a column vector. Its size is now N & 1. Thus, according to relationship (1.2) the dimensions of the product d 1⁄4 a*b0 are given by
(1 & N) % (N & 1) 1⁄4 (1 & 1); (1:4) that is, their product is a scalar. Moreover, d is computed according to Equation 1.3 as
Compute the dot product of the vectors a 1⁄4 [1, 2, 3] and b 1⁄4 [4, 5, 6]. Verify your result with the MATLAB command dot.
dij 1⁄4
XN p1⁄41
aipbpj, i1⁄41, j1⁄41, (1:5) which is equivalent to Equation 1.1 that describes the dot product of vectors.
Example
Commands
Results
Comments
Definition of the row vectors a and b. The transpose operator converts b into a column vector.
The size of a is 1&3, while the size of b0 is 3&1.
The dot product is computed as a % b0 . Notice that we do not use the dot operator before the multiplication operator as we implement a multiplication between matrices.
Verification of the result with use of the command dot.
ans1⁄44 5 b0 6
a1⁄41:3; b1⁄44:6;
size(a) size(b0 )
d1⁄4a*b0 dot(a,b)
ans1⁄41 3 ans1⁄43 1
d 1⁄4 32 ans 1⁄4 32
1.7.5 Power of a Matrix
In order to raise a matrix A to a power, A must be a square matrix; that is, the number of rows must be the same as the number of columns. The power of a matrix is actually a multiplication of the matrix with itself as many times as the power is. To raise each element of a matrix to a power, the dot operator is inserted before the power operator.
22
Signals and Systems Laboratory with MATLAB1
Commands
A 1⁄4 [1 2 3;4 5 6;7 8 9]
Results
A1⁄4123 4 5 6 789
Comments Square matrix A of size 3 & 3.
A is raised in the power of 3.
A is multiplied 3 times with itself.
The result is same as A^3.
Per element power of 3 of matrix
A. The result is different to the two previously obtained.
ans 1⁄4 468 A^3 1062
576 684
ans 1⁄4 468 A*A*A 1062
576 684
ans 1⁄4 1 A.^3 64
8 27
125 216
512 729
1305 1548 1656 2034 2412
1305 1548 1656 2034 2412
343
1.7.6 Inverse of a Matrix
The inverse matrix of a matrix A is denoted by A”1. If A”1 is multiplied with A, their product is the identity (or unit) matrix I, that is, a matrix with ones in the main diagonal and zeros elsewhere. The command that creates the inverse matrix of a matrix A is inv(A). Alternatively, the inverse matrix is computed by typing A^”1.
Commands
A1⁄4 [246;111;341]
B 1⁄4 inv(A)
C 1⁄4 A^”1
A*B 0.0000 1.0000
ans 1⁄4 1.0000 0.0000 B*A 0.0000 1.0000
0.0000 0
1.7.7 Determinant of a Matrix
B 1⁄4 “0.3750 0.2500 0.1250
2.5000 “0.2500 “2.0000 0.5000
C 1⁄4 “0.3750 0.2500 0.1250
0.5000 “0.2500 2.5000 “0.2500
ans 1⁄4 1.0000 0.0000 0.0000 0.0000
0
0 1.0000
0.0000
0.0000
1.0000
Results
Comments
MatrixAofsize3&3. The inverse matrix of A.
Second way of computing the inverse matrix A”1.
Indeed the product A % A”1 is equal to the identity matrix I.
In this case the commutative property stands, that is, A % A”1 1⁄4 A”1 % A 1⁄4 I.
A1⁄4246 1 1 1 341
“2.0000 0.5000 0.5000 “0.2500
The inverse of a matrix A does not always exists. The necessary conditions for the existence of the inverse matrix are (a) A must be square and (b)A must be invertible. A matrix is invertible if its determinant is not zero. The determinant of a matrix is calculated by executing the command det(A).
Introduction to MATLAB1 Commands
23
Results
Comments Matrix A of size 2 & 3.
A 1⁄4 [1 2 3; 4 5 6] inv(A)
A1⁄4 [246;111;341] det(A)
inv(A)
B 1⁄4 [1 1 1; 2 2 2; 3 3 3] det(B)
inv(B)
A1⁄4123 456
??? Error using ) inv Matrix must be square.
A1⁄4246 111 341
ans 1⁄4 8
ans 1⁄4 “0.375 2.500
A is not square, hence the inverse matrix does not exists.
Square matrix A of size 3 & 3.
The determinant of A is not zero; thus A
is invertible.
The inverse matrix A”1.
“0.250
Square matrix B of size 3 & 3.
“0.250 0.250 “2.000 0.500
0.125 0.500
B1⁄4111 222 333
ans1⁄40
Warning: Matrix is singular to working precision. (Type ‘‘warning off MATLAB:singularMatrix’’
to suppress this warning.)
The determinant of B is zero; thus B is not invertible.
Indeed the inverse matrix B”1 cannot be computed.
ans 1⁄4 Inf Inf Inf
Inf Inf Inf Inf Inf Inf
1.7.8 Division of Matrices
The division between matrices is defined in MATLAB as the product of the first matrix with the inverse of the second matrix if left division is applied, and vice versa if right division is applied. In other words, A=B 1⁄4 A % B”1 and AnB 1⁄4 A”1 % B. As usual, if the dot operator is employed the division is implemented as an element per element operation.
24
Signals and Systems Laboratory with MATLAB1
Commands
A1⁄4 [246;111;341]; B1⁄4 [322;141;321];
A=B
A*inv(B)
AnB inv(A)*B C1⁄4 A.=B
1.7.9 Transpose of a Matrix
ans 1⁄4
ans 1⁄4
ans 1⁄4
ans 1⁄4
Results
4.8000 0.8000 0.6000 0.1000 “0.4000 0.6000
4.8000 0.8000 0.6000 0.1000 “0.4000 0.6000
Comments
Invertible square matrices A and B.
Left division.
Equivalent operation to left division.
Right division.
Equivalent operation to right division.
C 1⁄4 0.6667
1.0000
1.0000
Element per
division, that is, cij 1⁄4 aij=bij.
0.6250
0.2500
0.1250
“4.4000 “0.3000 1.2000
“4.4000 “0.3000 1.2000
8.7500
“6.5000 “1.0000 1.7500 0.5000
0.6250 8.7500 1.5000
0.2500
0.1250
“6.5000 “1.0000 1.7500 0.5000
2.0000 3.0000 0.2500 1.0000 2.0000 1.0000
1.5000
element
The transpose of a matrix A (usually denoted by AT) is a matrix whose rows are the columns of A and its columns are the rows of A. Let B denote the transpose of A. The elements of B represented by bij are given by bij 1⁄4 aji. The transposed matrix AT is derived by applying the transpose operator (0> after matrix A, i.e., by typing B1⁄4A0.
Commands Results
A1⁄4123 A 1⁄4 [1 2 3; 4 5 6;7 8 9]; 456 789
B1⁄4147 B1⁄4A0 258 369
Comments MatrixAofsize3&3.
The transposed matrix AT .
3
ans 1⁄4 1 2
B0 456 789
A 1⁄4 [1 2 3; 4 5 6] A1⁄4123 456
B1⁄41 4 B1⁄4A0 25 36
Transposing AT results the initial matrix A. Matrix A of size 2 & 3.
The transpose of A is of size 3 & 2.
Introduction to MATLAB1 25
Remark
Recall that the transpose operator (0> was employed to convert a row vector into a column vector and vice versa.
Remark
The transpose of a matrix must not be confused with the inversion of a matrix.
1.7.10 Special Forms of Matrices
ones–zeros–rand-eye-magic-hilb
The command ones(M,N) creates a matrix of size M & N with ones. Typing ones(M) returns a square matrix with ones. Similarly, the command zeros(M,N) creates a matrix of size M&N with zeros. The command rand(M,N) returns an M&N matrix with random (see Section 1.17 for details) elements. The command eye(M,N) defines an M&N matrix with ones in the main diagonal and zeros elsewhere. The command magic(M) creates a square matrix with the property that the sum of each row or column is equal. Finally, the command hilb(N) returns an N & N Hilbert matrix.
Commands Results
ones(2,3) ans 1⁄4 111 111
zeros(1,4) ans 1⁄4 0000 ans 1⁄4 0.9501 0.4860
rand(3) 0.2311 0.8913 0.6068 0.7621
0.4565
0.0185
0.8214
Comments
Matrix of size 2 & 3 with ones.
Matrix of size 1 & 4 (or vector of length 4) with
zeros.
Matrix of size 3 & 3 with random elements. If there is one input argument to the command, the obtained matrix is square.
Matrix of size 4 & 2 with ones in the main diagonal and zeros elsewhere.
The identity matrix I of size 3 & 3. Magic matrix.
Hilbert matrix.
eye(4,2)
ans 1⁄4 1 0 0 1 0 0 00
ans 1⁄4 10 0 eye(3) 01 0 001
A1⁄4816 A 1⁄4 magic(3) 357 492
ans 1⁄4 1.0000 0.5000 hilb(3) 0.5000 0.3333 0.3333 0.2500
0.3333
0.2500
0.2000
26 Signals and Systems Laboratory with MATLAB1 1.7.11 Useful Commands
diag-triu-tril-toeplitz-hankel-find-sum-rank-norm-eig
In this section, we introduce some other commands that are applicable to matrices.
Commands
A 1⁄4 [1 2 3;4 5 6;7 8 9] diag(A)
B 1⁄4 diag([“1 2 3]) triu(A)
tril(A) toeplitz(A)
hankel(A)
find(B)
find(B>2) sum(A)
sum(A,2)
sum(sum(A))
rank(B)
norm(B)
eig(B)
Results
A 1⁄4 1 2 3 456 789
ans1⁄4 1 5 9
B1⁄4″1 0 0 020 003
ans1⁄4 1 2 3 056 009
ans 1⁄4 1 0 0 450 789
ans 1⁄4 1 4 7 2 5 8 3 6 9 414725836 741472583
ans 1⁄4 1 4 7 2 5 8 3 6 9 472583690 725836900 258369000 583690000 836900000 369000000 690000000 900000000
ans 1⁄4 1 5 9
ans 1⁄4 9
ans 1⁄4 121518
ans 1⁄4 6 15
24 ans 1⁄4 45
ans 1⁄4 3 ans 1⁄4 3
ans 1⁄4 “1 2
3
Comments MatrixAofsize3&3.
Command diag returns a column vector with the elements of the main diagonal.
Command diag can be also used to create a diagonal matrix. The elements of the main diagonal are the ones given as input to the command, while all other matrix elements are zero.
Conversion to an upper triangular matrix. Conversion to a lower triangular matrix. Conversion to a Toeplitz matrix.
Conversion to a Hankel matrix.
The command find returns the indices of the nonzero elements of B. The matrix is considered vector, hence the indices are scalars.
Returns the indices of elements that are larger than 2. The sum of each column of A.
The sum of each row of A. The sum of all elements of A.
The rank of a matrix is the number of linearly independent rows or columns.
The norm of B.
The eigenvalues of B. With the proper syntax the
command eig returns also the eigenvectors of a matrix.
Introduction to MATLAB1 27
1.8 Plotting with MATLAB
MATLAB is a very reliable and powerful tool for plotting. A graph is constructed as a set of points in two or three dimensions. These points are (typically) connected with a solid line. Commonly the graph of a function is desired. However, in MATLAB a plot is done using vectors or matrices and not functions.
1.8.1 Plotting in Two Dimensions
Suppose that we want to plot a function y(x), where x is the independent variable. The procedure to plot y(x) is as follows: First the vector x is created, such as a x b, where a, b are scalars. The function y(x) will be plotted over the interval [a, b]. Next, we create the vector y, which is of the same length as x; that is, the two vectors have an equal number of elements. The value of each element of y is the value of y(x) calculated for each element of x. Finally, the function y(x) is plotted by typing plot(x,y).
Example
Plot the function y(x) 1⁄4 x2, “2 x 2.
Commands
x1⁄4″2:2 length(x)
y1⁄4x.^2 length(y)
plot(x,y)
Results
x1⁄4″2 “1 0 1 2 ans 1⁄4 5.00
y1⁄441014 ans 1⁄4 5.00
4 3 2 1 0
−2 −1.5 −1 −0.5 0 0.5 1 1.5 2
Comments
Vector x is defined from “2 to 2 with step 1.
Vector x has 5 elements.
Vector y is created. Notice that y1⁄4[(“2)2(“1)2021222]. Also notice the dot operator which is inserted before the power operator to ensure that this is an element per element operation.
Vector y has the same number of elements to x.
Graph of the function y(x) 1⁄4 x2, “2 x 2.
The obtained graph of y(x) 1⁄4 x2, “2 x 2 is not exactly what was expected. This is due to the way that the command plot works. As mentioned before, the graph is done at the points [x(1), y(1)], [x(2), y(2)],…and next these points are connected with solid line. More specifically, in this graph the points with coordinates [“2, 4],[“1, 1],[0, 0],[1, 1],[2, 4]
28 Signals and Systems Laboratory with MATLAB1
are connected. In order to achieve a better graph, more points in the vector x and consequently in y are required. Therefore, by using a smaller step in the definition of x a better graph of y(x) is obtained.
Commands
Results
Comments
The vector x is defined from “2 to 2 with step 0.1.
Trying to execute the command plot we get an error warning as length(x) 1⁄4 41 and length(y) 1⁄4 5.
Vector y has to be redefined according to the new vector x.
Now the two vectors have the same number of elements and the function y(x) 1⁄4 x2, “2 x 2 can be plotted.
This time the graph is satisfactory.
It is possible to execute the command plot with only one input argument. The result appears to be correct. However, the x-axis is not the interval [“2 2] but [1 41]. More specifically, each element of y (recall that y consists of 41 elements) is plotted versus its index in the vector y and not versus the corresponding element of x.
x 1⁄4 “2:0.1:2
plot(x,y)
y 1⁄4 x.^2; length(y)
plot(x,y)
x 1⁄4 “2.00
“1.50 “1.40
“1.00 “0.90
“0.50 “0.40 “0.30 “0.20 “0.10
0 0.10 0.20 0.30 0.40 0.50 0.60
“1.90
“1.80 “1.70 “1.30 “1.20 “0.80 “0.70
“1.60 “1.10 “0.60
0.70 0.80 0.90 1.00 1.30 1.40 1.50 1.60 1.90 2.00
??? Error using ) plot Vectors must be the same lengths.
ans 1⁄4 41.00 4
3
2
1
1.10 1.20 1.70 1.80
plot(y)
0
−2 −1.5 −1 −0.5 0 0.5 1 1.5 2
4
3
2
1 0
0 5 10 15 20 25 30 35 40 45
Introduction to MATLAB1 29 1.8.2 The Fig File
The window in which a graph is displayed is known as figure. Figures are files with extension .fig. A figure can be saved outside MATLAB in the most common formats (jpg, eps, etc.). The file save dialog is depicted in Figure 1.2.
1.8.3 The Command linspace
A vector x is defined by specifying its initial value, the step, and its final value. The problem with this approach is that it is not always easy to calculate the number of elements that the vector consists of. For example, it is quite hard to estimate the number of elements of the vector defined by the statement x1⁄4[“2*pi:0.3:2*pi]. The command linspace provides an alternative way of creating vectors. The advantage is that the number of vector elements is defined through the command. The syntax is x 1⁄4 linspace(initial_ value,final_value,number_of_elements). The produced points, that is, the vector elements are equally spaced. The command logspace has the same use and syntax with linspace, but the points are logarithmically spaced. Moreover, the initial and final values are considered as powers of 10.
FIGURE 1.2
A figure can be exported from MATLAB in the most common formats.
30
Signals and Systems Laboratory with MATLAB1
Commands
x 1⁄4 linspace(0,1,5) x 1⁄4 0:1=4:1
ans 1⁄4 0 ans 1⁄4 0
Results
0.25 0.50 0.75 1.00 0.25 0.50 0.75 1.00
Comments
Vector x from 0 to 1 with 5 elements.
Equivalent vector creation.
The command logspace creates 5 logarithmically spaced points on the interval [100 101].
ans 1⁄4 1.00
1.8.4 Plotting Several Functions in One Figure
logspace(0,1,5)
1.78 3.16 5.62 10.00
It is possible to plot more than one function in the same figure by employing a different syntax of the command plot.
Example
Plot the functions y(x) 1⁄4 x2 cos(x), g(x) 1⁄4 xcos(x), and f(x) 1⁄4 2x sin(x),0 x 2p, in the same figure.
Commands
x 1⁄4 linspace(0,2*pi,100);
y 1⁄4 (x.^2).*cos(x); g 1⁄4 x.*cos(x);
f 1⁄4 (2.^x).*sin(x);
plot(x,y,x,g,x,f)
Results
Comments
Definition of vector x. Definition of vectors
y, g, and f.
Using this syntax of the command plot, it is possible to plot many functions in the same figure. Each function is plotted in different color.
40 20 0 −20
−400 1 2 3 4 5 6 7
In the previous examples, the functions were plotted with predefined colors and line type (solid). It is possible to create a graph using colors, symbols used to draw the points, and type of line that connects the points of your choice. This is achieved by applying one more input argument to the command plot. The new argument is a series of special characters given in single quotes. The available special characters are presented in the table below.
Introduction to MATLAB1
31
Symbol Color
b Blue
g Green
r Red
c Cyan
m Magenta y Yellow k Black
w White
Symbol
. o x þ * s d
<, > p
h
Point Type Symbol
Point – Circle : x-mark -. Plus – Star
Square Diamond Triangle Pentagram Hexagram
Results
Line Type
Solid Dotted Dashdot Dashed
Comments
Commands
x 1⁄4 linspace(“1,1,15); y1 1⁄4 asin(x);
y2 1⁄4 acos(x);
Definition of vector x. Definition of vectors
y1 and y2.
The first function is plotted by black
2 plot(x,y1,’k:p’,x,y2,’r–o’) 1
0 −1 −2
pentagons
dotted line, while the second function is plotted by red circles with dashed line.
plot(x,y1,’Color’,[1 0 1], ‘Linewidth’,4)
−1
−2−1
−0.8 −0.6 −0.4
0.6 0.8 1
4
3
−1 −0.8 −0.6 −0.4
−0.2 0 0.2 0.4 0.6 0.8 1
with
Another available syntax of the command plot that specifies the color and the line width is presented below.
Commands
Results
−0.2 0 0.2 0.4
Comments
The vector that appears after the text ‘‘Color’’ specifies the RGB elements that take values on [0 1]. Number 4 determines the line width.
2
1
0
32 Signals and Systems Laboratory with MATLAB1
If one plots a new graph, by executing the command plot the old graph is discarded. A command that can be used in order to hold the current plot and draw the next one in the same figure is the command hold. This command can be used as a switch between the two modes (preserve graph=discard graph). More easily, one can type hold on to apply the preserve graph state and hold off to return to the default mode.
Commands
Results Comments
x 1⁄4 linspace(0,2*pi,150); plot(x,cos(x));
Definition of vector 0 x and direct plot
hold on
plot(x,sin(x));
hold off
plot(x,tan(x))
−0.5
−10 1 2 3 4 5 6 7
1 0.8 0.6 0.4 0.2
of cos (x).
The old graph is preserved.
1.8.5 Formatting a Figure
1 0.5
The new function 0 is plotted together
−0.2 with the old one. −0.4
−0.6 −0.8
−10 1 2 3 4 5 6 7
100 80 60
Switch to the non- hold mode.
40 The old graph is 20 discarded and the
0
−20 new function is
−40 −60 −80
−1000 1 2 3 4 5 6 7
plotted alone.
grid-title-xlabel-ylabel-legend-text-gtext-axis-xlim–ylim
The command grid on adds grid lines to the graph, while the command grid off removes the grid lines. Simply typing grid is a switch between the two modes. Text beside the x-axis and y-axis can be added using the commands xlabel and ylabel, respectively. A graph title is inserted by the command title.
Introduction to MATLAB1
33
Commands Results
1 0.8 0.6 0.4
x 1⁄4 linspace(0,2*pi,150); 0.2 0
Comments
Definition of the vector x and plot of cos (x) and sin (x).
Insertion of grid lines.
Labels in the axes and graph title.
plot(x,cos(x),’r*’,x,sin(x),’k’) −0.2 −0.4 −0.6 −0.8
grid
−10 1 2 3 4 5 6 7
1 0.8 0.6 0.4 0.2 0 −0.2 −0.4 −0.6 −0.8
−10 1 2 3 4 5 6 7
1 0.8 0.6 0.4 xlabel(‘x-axis’) 0.2
y−Axis
ylabel(‘y-axis’) 0 −0.4
title(‘Graph of cos(x) and sin(x)’) −0.2 −0.6 −0.8
Graph of cos(x) and sin(x)
−10 1 2 3 4 5 6 7
x−Axis
Text can be added at a specific point in the plot by typing the command text(x,y,’string’), where (x,y) are the coordinates of the point where the string written in the quotes is displayed. A simpler way to insert text inside the graph is to use the command gtext(‘string’), where the text is inserted at a position indicated with the mouse. The command legend(‘string1’, ‘string2′, . . . ) puts a legend on the current plot using the specified strings as labels. The legend is erased by typing legend off. Finally, the command axis([x_min, x_max, y_min, y_max]) specifies the limits for the two axis. If only the limits of the x-axis need to be changed the command xlim([x_min, x_max]) is appropriate. Similarly, executing the command ylim([y_min, y_max]) sets the limits of y-axis.
34
Signals and Systems Laboratory with MATLAB1
Commands
Results
Graph of cos(x) and sin(x) “string 1”
“string 2”
Comments
The text ‘‘string1’’ is placed at the point with coordinates [3 0.3], while the text ‘‘string2’’ is placed with the mouse. The legend command clarifies which function corresponds to which curve. The legend is by default placed at the upper left part of the graph.
cos(x) sin(x)
text(3,0.3,’string1’) 0.4 gtext(‘string2’) 0.2
x−Axis y−Axis
−0.2 legend(‘cos(x)’,’sin(x)’) 0
axis([2,4,”1,0])
1.8.6 Plotting in Different Figures
1 0.8 0.6
cos(x) sin(x)
−0.4 −0.6 −0.8
−10 1 2 3 4 5 6 7
0 −0.2 −0.4 −0.6 −0.8
x−Axis
Graph of cos(x) and sin(x)
string 2
Change of limits. The x-axis is at [2 4] and the y-axis is at [“1 0].
−12 3 4
x−Axis
Up to this point, all plots were made in a single figure named Figure 1. By typing at the command prompt figure, a new figure with name Figure 2 appears without closing the old figure. Typing figure(k) creates a new figure with name Figure k. This is the active figure where the next graph will appear. The command subplot(m,n,p) or subplot(mnp) splits the figure window into m & n small subfigures and makes the pth subfigure active.
Introduction to MATLAB1 Commands
figure
35
Results
Comments
A new figure with name Figure 2 is created. The old figure is preserved.
x1⁄40:.1:2*pi; plot(x,x.*exp(“x));
The window Figure 2 is the active one, i.e., the next graph is plotted in it.
subplot(2,3,5)
The figure is split in 2 & 3 1⁄4 6 subfigures. The active subfigure is the fifth.
(continued)
36
Signals and Systems Laboratory with MATLAB1
(continued)
Commands
plot(x,x.*exp(“x))
Results
Comments
Plotting in the active subfigure.
subplot(2,3,3)
Activation of the third subfigure.
1.8.7 Commands for Plotting
loglog-semilogx-semilogy-area-fplot-ezplot
Besides plot there are also some other commands that can be employed for plotting a function. Suppose that x and y are the two available vectors. The command loglog(x,y) plots y versus x with both axis being logarithmically scaled. Typing semilogx(x,y) only the x-axis is in logarithmic scale, while typing semilogy(x,y) only the y-axis is in logarithmic scale. The command area(x,y) produces a stacked area plot. The command fplot provides an easy way of plotting a function without the need to specify vectors. Its syntax is fplot(‘fun’,[x_min,x_max]), where fun is the function that is plotted in the interval [x_min, x_max]. A related command with a similar syntax is the command ezplot. Additionally, ezplot is useful when plotting symbolic expressions. Symbolic expressions are discussed in Section 1.15.
Introduction to MATLAB1 Commands
Results
37
Graph of the function y(x) 1⁄4 2xþ30, 1 x 100.
Graph of y(x) in logarithmic scale axes.
Graph of y(x) with the x-axis being logarithmically scaled.
Graph of y(x) with the y-axis being logarithmically scaled.
A stacked area plot of y(x).
(continued)
Comments
x 1⁄4 1:100; y 1⁄4 2*xþ30; plot(x,y)
loglog(x,y)
semilogx(x,y)
semilogy(x,y)
area(x,y)
250 200 150 100
50
00 10 20 30 40 50 60 70 80 90 100 103
102
1010 1 2 10 10 10
250 200 150 100
50
0012 10 10 10
103
102
1010 10 20 30 40 50 60 70 80 90 100 250
200
150
100 50
00 10 20 30 40 50 60 70 80 90 100
38
Signals and Systems Laboratory with MATLAB1
(continued)
Commands
250 fplot(‘2*xþ30’,[1,100]) 200
Results
50
00 10 20 30 40 50 60 70 80 90 100
1.8.8 Plotting Discrete-Time Functions
Comments
Fast ways of plotting y(x). By using fplot or ezplot there is no
%or 150
ezplot(‘2*xþ30′,[1,100])
100
need to vectors.
create
The command stem
A discrete time function is a function of the form f [n], n 2 Z, where Z denotes the set of integer numbers. In this case, the appropriate command for plotting a function f [n] is the command stem(n,f). The command stem plots the data sequence given in vector f versus vector n. The graph consists of lines from the x-axis terminated with circles on the data value.
Commands Results
n1⁄4″3:3 n1⁄4″3 “2 “1 0 1 2 3 f1⁄4n.^2 f1⁄49410149
Comments
The step used in vector n is 1. The function f [n] 1⁄4 n2 is defined.
9
8
7
6
5 “3 n 3 with use
stem(n,f)
stem(n,f,’r*’)
4 3 2 1
0−3 −2 −1 0 1 2 3
9 8 7 6 5 4 3 2 1
0−3 −2 −1 0 1 2 3
Graph of f[n] 1⁄4 n2, of the command stem.
This syntax of stem creates a graph with red stars.
Introduction to MATLAB1 39 1.8.9 Graph in Polar Coordinates
In MATLAB it is possible to create a plot using polar coordinates. The command is polar(theta,r), where theta is the vector of angles given in radians and r is the vector of distances from the axis origin.
Commands
theta1⁄4linspace(0,4*pi,10) r 1⁄4 theta
Results
theta 1⁄4 0 1.3963 2.7925
Comments
The function r 1⁄4 u is plotted, where r is the radius and u defines the angles in radians.
r 1⁄4 0 5.5851
9.7738
120 150
180
4.1888
12.5664
4.1888
8.3776
12.5664
5.5851
9.7738
6.9813
11.1701
1.3963
6.9813
11.1701
90
15
10 5
60
2.7925
8.3776
30
330
Graph
function
using
coordinates of the angle versus the radius. This syntax of polar creates a plot made of stars.
of the
r 1⁄4 u polar
polar(theta,r,'”*’)
0
210
240
270
300
1.8.10 Piecewise Functions
In this section, we discuss the way of defining and plotting functions with more than one part.
Example
Plot the function
8<:1, "2 t 2 f(t)1⁄4 0, 2
3<5 ans1⁄41
2$1⁄42 ans1⁄40
5>1⁄45 ans1⁄41
5<1⁄44 ans1⁄40
eq(20,20) ans1⁄41
gt(5,3) ans1⁄41
lt(5,3) ans1⁄40
ne(2,3) ans1⁄41
ge(4,5) ans1⁄40
le(5,5) ans1⁄41
Logical operations can be also implemented between matrices. Some related commands are given in the following table.
Command
isequal(a,b)
isempty(a)
isnan(a)
isinf(a)
Explanation
Returns 1 if matrices a and b are equal.
Returns 1 if matrix a has no elements.
Returns 1 if argument a is NaN.
Returns 1 if argument a is infinity.
Examples
a1⁄4[1 2]; b1⁄4[1 2]; isequal(a,b)
ans 1⁄4 1
isempty(a) ans 1⁄4 0 a1⁄4[]; isempty(a) ans 1⁄4 1
a1⁄40=0
Warning: Divide by zero. a 1⁄4 NaN
isnan(a)
ans 1⁄4 1
a1⁄41=0
Warning: Divide by zero. a 1⁄4 Inf
isinf(a)
ans 1⁄4 1
58 Signals and Systems Laboratory with MATLAB1 Finally, there are also logical operators.
Operator
Explanation
Example
1&0 ans 1⁄4 0
1j0
ans 1⁄4 1
$0
ans 1⁄4 1
xor(1,1) ans 1⁄4 0
a1⁄4[1 2]; b1⁄4[3 2]; all(a0 &a<5)
disp('fail')
elseif (a>1⁄45 & a<1⁄410)
disp('pass') else
disp('choose again') end
% File!Save as‘‘if1.m’’ if1
a 1⁄4 input('mark?') if (a>0 &a<5)
disp('fail') end
if (a>1⁄45 & a<1⁄410) disp('pass')
end
if (a< 1⁄4 0 ja>10)
disp(‘choose again’) end
% File!Save as‘‘if2.m’’ if2
a 1⁄4 input(‘mark?’) switch(a)
case{1,2,3,4} disp(‘fail’)
case{5,6,7,8,9,10} disp(‘pass’)
otherwise
disp(‘choose again’)
end
% File! Save as‘‘swi.m’’ swi
Results
mark ? 3 fail
Comments
The statements if-elseif-else.
The user input is number 3. Notice the use of
the logical operator & (i.e., AND).
The requested program is implemented using the simple syntax of the if statement. Notice the use of the logical operator j (i.e., OR).
The statement switch. Program swi.m is equivalent to the two previous implementations.
mark?16 choose again
mark ? 8 pass
60 Signals and Systems Laboratory with MATLAB1
The command for is used to repeat statements a specific number of times. The syntax is
for counter 1⁄4 vector Statements
end
The command while is used to repeat statements an indefinite number of times. The syntax is
while (condition) Statements
end
The command break is employed in order to stop a loop (for or while loop) before its completion. The command continue passes control to the next iteration of loop, i.e., it is used to stop one step of a loop. The command return is usually employed in functions to cause an early stop. Finally, with the key combinations Ctrl-C and Ctrl-Break one can terminate any statement under execution. To illustrate the use of loops several examples are given below.
M-Files and Their Execution from the Command line
% a 1⁄4 1:5
% for i1⁄4a for i 1⁄4 1:5
b(i)1⁄4i^2; end
display(b)
% File! Save as”for1.m” for1
a1⁄41; while(a> 1⁄4 0)
disp(‘positive to loop’) disp(‘negative to exit’) a 1⁄4 input(‘enter number’);
end
% File! Save as‘‘while1.m’’ while1
Results
b1⁄41 4 9 16 25
positive to loop, negative to exit enter number 89
positive to loop, negative to exit enter number 2
positive to loop, negative to exit enter number -5
Comments
Loop implemented with the command for. The comments at the first 2 lines illustrate an alternative way to define the loop- counter i. In this program, a for-loop is used to create a vector whose elements are the squares of the numbers 1 to 5
Loop implemented with command while. Notice that variable a must be initialized before being used in the loop. In this program, the loop continues as long as the user input is not a negative number.
Introduction to MATLAB1 (continued)
M-Files and Their Execution from the Command line
a1⁄41; while(1)
a 1⁄4 input(‘Mark ?’) if (a>0 & a<5)
disp('fail')
break;
elseif (a>1⁄45 & a<1⁄410)
disp('pass')
break; else
disp('choose again'); end
end
% File! Save as‘‘while2.m’’ while2
clear; for i 1⁄4 1:5
if (i1⁄4 1⁄43) continue;
end
b(i) 1⁄4 i^2; end
display(b)
% File-> Save as ‘‘cont1.m’’ cont1
function B 1⁄4 det1(A) if det(A) 1⁄4 1⁄4 0
disp(‘ non invertible matrix’) B1⁄4NaN;
return
else
B 1⁄4 inv(A);
end
% File-> Save as ‘‘det1.m’’ B 1⁄4 det1([2 2;1 1]);
61
Results
Mark ? 11 choose again Mark ? -6 choose again Mark ? 7
pass
b1⁄41 4 0 16 25
non invertible matrix
Comments
By typing while(1) an infinite loop is created. In order to terminate the infinite loop the command break is used. In this program, if the user input is not valid (i.e., between 1 and 10) the user is requested to enter again his mark.
Using the command continue causes the non-execution of the statements for i 1⁄4 3. The command continue is used together with an end statement.
The command return terminates the function det1.m if the matrix determinant is zero. Notice that a value must be assigned to the output argument of the function. Hence, we set B1⁄4NaN.
Finally, something that should be mentioned is that when programming with MATLAB we should avoid using loops as they are computationally expensive. Most of the times, the same process can be implemented using vectors=matrices.
Commands Results Comments
for i 1⁄4 1:10
a(i)1⁄4i^2; a1⁄41 4 9 16 25 36 end 49 64 81 100
a
i1⁄41:10; a1⁄41 4 9 16 25 36 a1⁄4i.^2 49 64 81 100
Implementation with loop. Implementation with vectors.
62 Signals and Systems Laboratory with MATLAB1
1.15 Symbolic Variables
The types of variables defined and used so far are matrices, vectors, scalars, and strings. In MATLAB, another variable type is available: the symbolic variable (or object). A symbolic variable is defined by the commands sym and syms. More specifically, by typing x1⁄4 sym(‘x’) or syms x y z if more than one symbolic variable is needed, the variables x y z are defined as symbolic variables. The use of symbolic variables allows the computation of limits, integrals, derivatives, etc.
Commands
x 1⁄4 sym(‘x’)
a 1⁄4 limit(sin(x)=x,0)
syms y z w
y z w
A 1⁄4 [x 2*y; z”w,zþw] det(A)
F1⁄4 2*x^2þ3*xþ4
Results
x1⁄4x a1⁄41
y1⁄4y z1⁄4z w1⁄4w
Comments
Definition of the symbolic variable x.
Computation of limx!0 ( sin (x)=x).
Easy way to define multiple symbolic variables.
Confirmation that y, z, and w are symbolic variables.
Symbolic matrices can be also defined. The determinant of A.
Polynomial of symbolic variables. The use of dot operator before the power operator is not necessary since x is not a vector but a symbolic variable. F is called a symbolic expression.
A 1⁄4 [x, 2*y] [z”w, zþw]
ans 1⁄4 x*zþx*w”2*y*zþ2*y*w F 1⁄4 2*x^2þ3*xþ4
1.15.1 Differentiation of a Function
To compute the derivative of a function f (x), first x must be declared as a symbolic variable. Then, the function f is defined in terms of the independent variable x and the derivative is computed by typing the command diff(f). Typing diff(f,n) returns the nth derivative of f (x). If the function has several symbolic variables, the syntax diff(f,variable,n) returns the nth partial derivative with respect to the variable specified in the diff command.
Example
Compute the partial derivatives of the function f (x, y) 1⁄4 e”x cos (y).
Introduction to MATLAB1
63
Commands
syms x y
f 1⁄4 exp(“x)*cos(y) diff(f,x) diff(f,y) diff(f,x,2)
t 1⁄4 diff(f,x) diff(t,x)
Results
f 1⁄4 exp(“x)*cos(y) ans 1⁄4 “exp(“x)*cos(y) ans 1⁄4 “exp(“x)*sin(y) ans1⁄4 exp(“x)*cos(y)
t 1⁄4 “exp(“x)*cos(y) ans 1⁄4 exp(“x)*cos(y)
Comments
Declaration of the symbolic variables x and y. The function f(x, y) is a symbolic expression. Partial derivative qf =qx.
Partial derivative qf =qy.
Second derivative of f with respect to x.
Alternative computation of the second derivative of f with respect to x. The result of the first derivative is assigned to variable t and the derivative of t is the desired result.
1.15.2 Integration of a Function
The command used to compute the integral of a function is the command int. Suppose that f is a function. Typing int(f,variable) returns the indefinite integral of f with respect to the variable specified at the int command. Of course, it is not always possible to compute an integral or write the integration result in a closed-form expression. A definite integral is computed by int(f,variable,lower-limit,upper-limit).
Commands
syms x t f1⁄4x^2
g 1⁄4 x^2þexp(“t) int(f,x) pretty(ans) int(f,x,”1,1)
int(exp(“x^2),x,”inf, inf) z 1⁄4 int(g,x)
int(z,t)
Results
f1⁄4x^2
g 1⁄4 x^2þexp(“t)
ans 1⁄4 1=3*x^3 1=3 x3
ans 1⁄4 2=3
ans 1⁄4 pi^(1=2)
z 1⁄4 1=3*x^3þexp(“t)*x
ans 1⁄4 1=3*x^3*t”exp(“t)*x
Comments
Declaration of the symbolic variables x and t.
The functions f (x) 1⁄4 x2 and g(x, t) 1⁄4 x2 þ e”t are defined as symbolic expressions.
Computation of Ð x2dx.
The command pretty prints symbolic output in a format that resembles typeset mathematics.
1.15.3 Summation of a Function
The command symsum computes symbolic summations. The most convenient syntax is symsum(expresion, index,lower-limit, upper-limit).
Ð12 Computation of Д1 x dx.
Computation of the double indefinite integral Ð Ð g(x, t)dxdt.
Computation of 1 e”x2 dx. To define “1
+1 in MATLAB we write + inf. Note that the function can be directly defined inside the command int.
64
Signals and Systems Laboratory with MATLAB1
Commands
syms w k f 1⁄4 w^k
symsum(f,k,0,inf)
1.15.4 Rational Form
Results
f 1⁄4 w^k
ans 1⁄4 “1=(w”1)
Comments
Computation of P1 wk. k1⁄40
The result is 1=(1 ” w).
The command numden is employed in order to convert a function written in a complicated form into a simple rational expression. If f is the complicated expression, typing [n,d]1⁄4numden(f) returns the numerator n and the denominator d of the equivalent simplified rational expression of f.
Commands
syms x
f 1⁄4 (x^2)=(xþ4)þ3=(x”3)
[n,d] 1⁄4 numden(f)
Results
f 1⁄4 x^2=(xþ4)þ3=(x”3) n 1⁄4 x^3″3*x^2þ3*xþ12
d 1⁄4 (xþ4)*(x”3)
Comments
Definition of the symbolic variable x. The complicated written function is
x2 3
f (x) 1⁄4 x þ 4 þ x ” 3.
The numerator and denominator of the rational form of f(x), or in other
words, f(x) 1⁄4 x3 ” 3×2 þ 3x þ 12. (xþ4)(x”3)
1.15.5 Solving Algebraic Equations
The command solve computes the roots of a symbolic expression f. The best practice is to specify the variable that you solve for, and not let MATLAB choose what is best for you.
Commands
syms x
f 1⁄4 x^2þ6*xþ5
solve(f,x) solve(‘x^2þ6*xþ5 1⁄4 0’,x)
Results
f 1⁄4 x^2þ6*xþ5 ans 1⁄4 [“5]
[“1] ans 1⁄4 “1
“5
Comments
Definition of the symbolic variable x. The expression x2 þ6xþ51⁄40 is
assigned to variable f.
Solving f for x. The roots are “5 and “1.
Direct computation of the solution of equationx2 þ6xþ51⁄40.
The command solve can be also applied when dealing with systems of two or more algebraic equations. The appropriate syntax in this case is solve(‘eqn1′,’eqn2′, . . . ,’ eqnN’,’var1,var2,…,varN’), where eqnm denotes the mth equation and varm the mth variable to solve for.
Introduction to MATLAB1 65
Example
Compute x and y for the system y 1⁄4 2x þ 3 and y 1⁄4 4x þ 5.
Commands
[x,y] 1⁄4 solve(‘y 1⁄4 2*xþ3′,’y 1⁄4 4*xþ5′,’x,y’)
1.15.6 Solving Differential Equations
Results
x 1⁄4 “1 y1⁄41
Comments
Solution of a system of algebraic equations. Notice that it is not necessary to declare symbolic variables in order to use the command solve. Also notice that it is possible to assign the output of solve to a variable.
It is quite easy to solve ordinary differential equations, by using a similar to solve command, named dsolve. The syntax is dsolve(‘f’,’initial-conditions’, ‘independent-variable’), where f is a nth order differential equation, the initial con- ditions are the values (usually at zero) of the n”1 derivatives, while the independent variable is usually omitted. By default, t is considered as the independent variable. Regarding the definition of the differential equation f, the first derivative of y is denoted by Dy, the second derivative of y is denoted by D2y, and so on.
Example
Compute the solution of the differential equation y0(t) þ y(t) þ 1 1⁄4 0, y(0) 1⁄4 0.
Commands
f 1⁄4 ‘Dyþyþ1′
it1⁄4’y(0)1⁄40’
dsolve(f,it) dsolve(‘Dyþyþ1′,’y(0) 1⁄4 0′,’t’)
Example
Results
f 1⁄4 Dyþyþ1
it 1⁄4 y(0)1⁄40
ans 1⁄4 “1þexp(“t) ans 1⁄4 “1þexp(“t)
Comments
Definition of the differential equation. The quotes are required.
The initial condition, i.e., the value of y(t) at t 1⁄4 0 is defined. Again quotes must be used.
Solution of the differential equation. The independent variable is omitted.
Direct computation of the solution of the differential equation.
Compute the solution of the differential equation y00(t) ” 1 1⁄4 0, y(1) 1⁄4 1, y0(2) 1⁄4 2.
Commands
f 1⁄4 ‘D2y”1 1⁄4 0′ it1⁄4’y(1)1⁄41, Dy(2)1⁄42’
y 1⁄4 dsolve(f,it)
Results
f 1⁄4 D2y”1 1⁄4 0 it 1⁄4 y(1)1⁄41,
Dy(2)1⁄42
y 1⁄4 1=2*t^2þ1=2
Comments
Definition of the differential equation.
The conditions are the value of y(t) at t 1⁄4 1
and the value of y0(t) at t 1⁄4 2.
The function y(t) 1⁄4 (t2 þ 1)=2 is the solution
of the differential equation.
66 Signals and Systems Laboratory with MATLAB1 1.15.7 The Command subs
The command subs is used to replace one or more variables (symbolic or numerical) of a symbolic expression with some others. The syntax is subs(f,old,new), where f is the expression, old are the replaced variable(s), and new are the values or the variables that replace the old ones.
Commands
syms y x z
f 1⁄4 2*xþyþ4
w 1⁄4 subs(f,y,3) q 1⁄4 subs(w,x,z) subs(q,7,11)
symbolic expression.
Results
f 1⁄4 2*xþyþ4 w 1⁄4 2*xþ7
q 1⁄4 2*zþ7 ans 1⁄4 2*zþ11
ans 1⁄4 2*zþ7
The command subs is very useful as it makes possible the graph implementation of a
Comments
The symbolic expression f has two symbolic variables. Variable y is replaced by number 3.
Variable x is replaced by variable z.
Number 7 is replaced by number 11.
subs(f,[x,y],[z,3])
The variables x and y of the expression f are replaced by z and 3, respectively.
Commands
syms t y
y 1⁄4 t*exp(“t)
plot(t,y)
t1 1⁄4 0:.1:5;
y1 1⁄4 subs(y,t,t1); plot(t1,y1);
Results
Comments
The function y(t) 1⁄4 te”t is defined as symbolic expression.
Trying to plot y(t) in the usual way causes an error.
The symbolic variable t is replaced by the vector t1. The output y1 becomes also a vector. The plot of y(t) 1⁄4 te”t is done in the time interval specified from t1.
y 1⁄4 t*exp(“t)
??? Error using ) plot Conversion to double from sym is not possible.
0.4 0.35 0.3 0.25 0.2 0.15 0.1 0.05
00 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
1.16 Polynomials
There are many ways to represent a polynomial in MATLAB. The most convenient way is to represent it as a row vector whose elements correspond to the polynomial coefficients in descending order. Of course, if a polynomial term is missing (or in other words, its coefficient is zero), the corresponding vector element is set to zero. For example, the
Introduction to MATLAB1 67
polynomialp(x)1⁄42×3 þ5x”6isrepresentedbyp1⁄4[205″6].Supposethatpandqare vectors that represent the polynomials p(x) and q(x), respectively. Operations between p(x) and q(x) are implemented as follows:
. Addition and subtraction: If p(x) and q(x) are of the same order, then p and q are vectors of the same length and the operations of addition and subtraction are element per element operations. If p(x) and q(x) are not of the same order, the vector of smaller size must be padded at its beginning with zeros.
. Multiplication: The product p(x) % q(x) is computed by typing the command conv(p,q).
. Division: The command [a,b] 1⁄4 deconv(p,q) returns the quotient a and the remainder b of the division p(x)=q(x).
Commands
p1 1⁄4 [5 6]; p21⁄4[7 0 2];
p1⁄4conv(p1,p2)
[a,b] 1⁄4 deconv(p2,p1)
conv(a,p1)þb p11⁄4[0 5 6];
. Polynomial roots computation: The command r 1⁄4 roots(p) computes the roots of the polynomial p and stores them in a column vector r.
. If the roots r of a polynomial are known, typing p 1⁄4 poly(r) returns the coeffi- cients of the polynomial.
. The derivative of a polynomial is computed by the command h 1⁄4 polyder(p).
. Finally, to evaluate a polynomial p(x) at a specific value x0, i.e., to compute p(x0) the suitable command is polyval(p,x0).
ad1⁄4 p1þp2 sub1⁄4 p2″p1
ad1⁄47 5 8 sub 1⁄4 7 “5
p 1⁄4 35
a 1⁄4 1.40
b 1⁄4 “0.00
ans 1⁄4 7.00 0.00
12
12.08 2.00
p(x)1⁄435×3 þ42×2 þ10xþ12.
The ratio p2 (x)=p1 (x) is a(x) þ b(x)=p1 (x) 1⁄4
1:4x ” 1:68 þ 12:08=(5x þ 6). Confirmation of the polynomial division.
Indeed a(x)p1(x) þ b(x) 1⁄4 p2(x).
To add and subtract p1 (x) and p2 (x) one zero
Results
42 10
Comments
“1.68 0.00
element is padded in the beginning of vector p1. Other operations between polynomials that are supported in MATLAB are
“4
p1 (x) 1⁄4 5x þ 6 The product p1 (x)p2 (x) is the polynomial
Definition of the polynomials and p2(x) 1⁄4 7×2 þ 2.
Commands
p 1⁄4 [1 “0.5 3] r 1⁄4 roots(p)
p 1⁄4 poly(r)
h 1⁄4 polyder(p) polyval(p,2)
Results
r 1⁄4 0.2500 þ 1.7139i 0.2500 ” 1.7139i
Comments
Definition of the polynomial p(x) 1⁄4 x2 ” 0:5x þ 3 and computation of its roots.
Construction of the polynomial from its roots. The derivative of p(x) is h(x) 1⁄4 p0 (x) 1⁄4 2x ” 0:5. Evaluation of p(x) for x 1⁄4 2.
p 1⁄4 1.00
h 1⁄4 2.0000 ans 1⁄4 6
“0.50 3.00 “0.5000
68 Signals and Systems Laboratory with MATLAB1
1.17 (Pseudo)Random Numbers
rand-randn-hist-pie-mean-var
Random numbers are a subject of great importance and find applications in many areas of interest such as simulation or cryptography. In MATLAB, there is the possibility to generate random (or pseudorandom) numbers distributed according to a specific distribu- tion function. The command x 1⁄4 rand(N,K) returns a matrix of size N & K whose elem- ents are uniformly distributed in [0 1]. To create random numbers uniformly distributed in an interval [a, b] the associated statement is x1⁄4aþ(b”a)*rand(N,K). In order to generate normally distributed random numbers, we use the command randn. The syntax x 1⁄4 randn(N,K) returns a matrix of size N & K whose elements are distributed2according to the normal (or Gaussian) distribution with mean m 1⁄4 0 and variance s 1⁄4 1. The appropriate statement to generate random numbers distributed according to a normal distribution with mean m and variance s2 is x 1⁄4 mþ s*randn(N,K). The histogram of a vector x whose elements are random numbers is plotted by the command hist(x,k), where k is the numbers of bins. A pie plot of the data in vector x is implemented by the command pie(x). Finally, command mean(x) computes the mean value of the vector elements, while command var(x) calculates the variance of the values in x.
Commands
x 1⁄4 rand(4,3) x 1⁄4 2þ(5″2)*
Results
Comments
Matrix of 4 rows and 3 columns whose elements are uniformly distributed over the interval [0 1].
Matrix of 4 rows and 3 columns whose elements are uniformly distributed over the interval [2 5].
Matrix of 4 rows and 3 columns whose elements are distributed according to the normal distribution with mean m 1⁄4 0 and variance s2 1⁄4 1.
Matrix of 4 rows and 3 columns whose elements are distributed according to the normal distribution with mean m 1⁄4 4 and variance s2 1⁄4 25.
2000 random numbers uniformly distributed in [0 1] and the corresponding histogram.
x1⁄4 x1⁄4
x1⁄4
x1⁄4
250
200 x 1⁄4 rand(1,2000); 150
hist(x,10) 100 50
0.9218
0.7382
0.1763
0.4057
2.4167
2.6083
2.5962
3.8114
“0.4326 “1.6656 0.1253 0.2877
1.0584
14.9159
3.3180
4.5697
0.9355
0.9169
0.4103
0.8936
2.8166
2.5964
2.0458
4.2404
“1.1465 1.1909
1.1892 “0.0376
9.3338
4.2964
3.5218 “0.1617
0.0579
0.3529
0.8132
0.0099
3.3353
4.7954
3.3980
3.2559
0.3273
0.1746 “0.1867 0.7258
5.4721 “2.6809
7.5716
12.1178
rand(4,3)
x 1⁄4 randn(4,3)
x 1⁄4 4þ5*randn(4,3)
00 0.1 0.2
0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Introduction to MATLAB1 (continued)
69
Commands
m 1⁄4 mean(x) s2 1⁄4 var(x)
x 1⁄4 randn(1,2000); hist(x,10)
m 1⁄4 mean(x) s2 1⁄4 var(x)
Results
Comments
m 1⁄4 0.5020 s2 1⁄4 0.0845
500 400 300 200 100
Mean value and variance of the uniformly distributed random numbers. The estimated mean value of the samples approximates the true one which is given by (a þ b)=2 1⁄4 0:5. The estimated variance also approximates the true variance which is given by s2 1⁄4 (b ” a)2=12 1⁄4 0:0833.
2000 random numbers distributed according to the normal distribution with mean m 1⁄4 0 and variance s2 1⁄4 1 and the corresponding histogram.
Mean value and variance of the normally distributed random numbers. The estimated mean value of the samples approximates the true one which is m 1⁄4 0. The estimated variance also approximates the true variance whichiss2 1⁄41.
0
−4 −3 −2 −1 0 1 2 3 4
m 1⁄4 0.0012 s2 1⁄4 0.9783
1.18 Solved Problems Problem 1
. Create a vector a 1⁄4 [0,0:1,0:2,…,10] and a cos (0:4), . . . , cos (20)].
. Compute the following: c 1⁄4 a=b
d 1⁄4 a4
The dot product of a and b
Solution
a 1⁄4 0:.1:10;
b 1⁄4 cos ([0:.2:20]); c 1⁄4 a.=b;
d 1⁄4 a.^4;
prod 1⁄4 dot(a,b)
vector
b 1⁄4 [cos(0), cos(0:2),
70 Signals and Systems Laboratory with MATLAB1 Problem 2
1. Create a 3 & 3 matrix A whose elements are random numbers uniformly distributed in [0 1]. Compute
a. The inverse matrix.
b. The transpose of matrix A.
c. The determinant of A. d. The size of A.
e. The second column of A.
2. Create a sub-matrix B with the elements of the first and third rows of A.
Solution
1. A1⁄4 rand(3) a. inv(A) b. A0
c. det(A) d. size(A) e. A(:,2)
2. B1⁄4A(1:2:3,:)
Problem 3
a. Create a function that accepts as input argument a number in radians and returns its value in degrees.
b. Compute (through your function) how many degrees is p=4 radians. Solution
a. function y 1⁄4 degtorad(x) y 1⁄4 x*180=pi;
b. z 1⁄4 degtorad (pi=4);
% To verify your result execute the built-in MATLAB command deg2rad.m
Problem 4
a. Create a function that plots the function sinc(x) 1⁄4 sin (px)=(px). b. Plot (through your function) sinc(x) in the interval [“2p 2p].
Introduction to MATLAB1 71
Solution
a. function y 1⁄4 sink(x)
y 1⁄4 sin(pi*x).=(pi*x); plot(x,y);
There is a small problem at x 1⁄4 0. To see how to combat it open the built-in MATLAB command sinc.m by typing in the command prompt open sinc.
b. sink([“2*pi:.1:2*pi]);
Problem 5
a. Write a function that accepts as input arguments a vector x and two scalars m and s
1 “1ðx”mÞ2 and plots the function g(x) 1⁄4 pffiffiffiffiffiffi e 2 s .
s 2p
b. Plot y(x) for a vector x from “5 to 5, m1⁄40 and s1⁄41.
Solution
a. function g 1⁄4 gau(x,m,s)
g 1⁄4 (1=(s*sqrt(2*pi))) *exp(“0.5*( (x”m)=s).^2); plot(x,g);
b. gau([“5:.1:5], 0,1)
Problem 6
a. Write a function that accepts as input argument a complex number and returns as output
Its magnitude
Its angle
Its real part
Its imaginary part
b. Compute the above quantities for the complex numbers
i “i
1
e3þ4i
Solution
a. function [mag, ang, re, im] 1⁄4 comple(x) mag 1⁄4 abs(x)
ang 1⁄4 angle(x)
re1⁄4 real(x)
im 1⁄4 imag(x)
b. [a,b,c,d]1⁄4comple(i); [a,b,c,d] 1⁄4 comple(“i); [a,b,c,d] 1⁄4 comple(1); [a,b,c,d] 1⁄4 comple(exp(3þ4i));
72 Signals and Systems Laboratory with MATLAB1 Problem 7
. Generate a row vector of 500 linearly equally spaced points between 0 and 2p.
. Plot on the same figure in the interval [0 2p] the functions
f(x) 1⁄4 xe”x,0 x 2p and y(x) 1⁄4 2cos(x),0 x 2p.
. Add a title (of your choice) to the graph.
. Label the two axis of the graph.
. Insert a legend for all functions that appear in the graph.
. Plot the above functions at a second figure in two different subfigures.
Solution
x 1⁄4 linspace(0,2*pi,500); f 1⁄4 x.*exp(“x);
y 1⁄4 2.^cos(x); plot(x,f,x,y);
title(‘Two functions’); xlabel(‘x-axis’); ylabel(‘y-axis’); legend(‘f(x)’,’y(x)’); figure(2); subplot(211); plot(x,f); subplot(212); plot(x,y);
Problem 8
1 0.5 0 −0.5 −1
10 9 8 7 6 5 4 3 2 1 0 0 1 2 3 4 5 6 7 8 9
10
10 and z 1⁄4 0.
Plot the graph that is depicted above. Notice that 0
Solution
x 1⁄4 0:10;
y1⁄4x;
[X,Y] 1⁄4 meshgrid(x,y); Z 1⁄4 zeros(size(X)); mesh(X,Y,Z)
x 10, 0 y
Introduction to MATLAB1 73 Problem 9
a. Compute the partial dÐerivatives of the function f (x, t) 1⁄4 cos (x) þ sin (t) þ et. b. Calculate the integral 01 te”tdt. Ð 3 t
c. Calculate the double indefiPnite integral x e dxdt.
f. Find the solution of the equation f(x) 1⁄4 x3 þ 2×2 ” x ” 2. Solution
a. symsxtkwn
f 1⁄4 cos(x)þsin(t)þexp(t); diff(f,x);
diff(f,t);
b. x1⁄4t*exp(“t); int(x,t,0,inf)
c. f1⁄4(x^3)*exp(t); a 1⁄4 int(f,x);
b 1⁄4 int(a,t);
d. f1⁄4(x^k)=’k!’ symsum(f,k,0,inf)
e. f1⁄43=(xþ2)þx=(x^2þ1); [n,d] 1⁄4 numden(f); f1⁄4n=d;
f. f1⁄4x^3þ2*x^2″x”2 solve(f,x)
Problem 10 Compute and plot the solution of the differential equation y00(t) þ y(t) 1⁄4 1, y(0) 1⁄4 0,y0(0) 1⁄4 0.
Solution
syms y t
sol 1⁄4 dsolve(‘D2yþy 1⁄4 1′,’y(0) 1⁄4 0′,’Dy(0) 1⁄4 0′,’t’); t 1⁄4 “5:.1:5;
y 1⁄4 subs(sol,t);
plot(t,y)
Problem 11
a. Create a vector a with elements from 1 to 100. Store the data of a in a file with filename test.txt.
b. Create a vector b with elements from 100 to 1 and store the data of b in the file test.txt without deleting the data of a.
d. Compute the summation 1
e. Express in rational form the function f(x) 1⁄4 x þ 2 þ x2 þ 1.
xk.
k1⁄40 k! 3 x
74 Signals and Systems Laboratory with MATLAB1 c. Create a matrix B of size 1 & 200 and save in B the data of the file test.txt.
d. Save matrix B and vectors a and b in a file matrix.mat and next erase them from the memory.
e. Retrieve only matrix B from the file matrix.mat and load it in the memory. Solution
a. a1⁄41:100;
fid 1⁄4 fopen(‘test.txt’,’w’); fprintf(fid,’%f nn’,a); fclose(fid)
b. b1⁄4100:”1:1;
fid 1⁄4 fopen(‘test.txt’,’a’); fprintf(fid,’%f nn’,b); fclose(fid)
c. fid1⁄4fopen(‘test.txt’,’r’);
B 1⁄4 fscanf(fid, ‘%f’,[1,200]);
d. save matrix B a b
e. clearBab
load matrix B
Problem 12
a. Create a vector of 5000 random numbers distributed according to the normal distribution with mean m 1⁄4 5 and variance s2 1⁄4 3.
b. Plot the histogram.
c. Compute the mean value and the variance of the samples.
d. Create a vector of 5000 random numbers uniformly distributed in the interval from a1⁄41 to b1⁄410.
e. Plot the histogram.
f. Compute the mean value and the variance of the samples.
Solution
a. x1⁄45þsqrt(3)*randn(5000,1); b. hist(x,100)
c. mean(x) var(x)
d. x1⁄41þ9*rand(5000,1); e. hist(x,10);
f. mean(x); var(x);
Introduction to MATLAB1 75
1.19 Homework Problems
1. Display the numbers 1 through 10 as long as their squares and their square roots.
2. Compute the sum of the squares of the numbers 1 through 10.
3. Create a vector with elements !0, 2 , 4 , 6 ,…, 18”. 468 20
4. Create the vector x 1⁄4 [1,2,…,100]. Assign the even numbers of x to a vector y.
5. Create the vector x 1⁄4 [1, 2, . . . , 100]. Assign the numbers that are multiples of 3 to a
vector y.
6. Considerthevectorsadd1⁄4aþb1⁄4[1312111010]andsub1⁄4a”b1⁄4 [“11″6″148].
Find the vectors a and b.
7. Create an algorithm that computes the product of two matrices according to
Equation 1.3.
8. Plot the function f (t) 1⁄4 te”t, 0 t 5.
9. Consider the function h(t) 1⁄4 sinc(t=T) cos (pbt=T) . This function describes a raised 1″(4b2 t2 =T2 )
cosine filter in the time domain. Suppose that T 1⁄4 1 and b 1⁄4 0:5 and plot h(t) in the
time interval “5T t 5T.
10. Split a figure into six subfigures and plot the function h(t) described in the previous exercise combining each time the values T 1⁄4 1 and T 1⁄4 3 with b 1⁄4 0, b 1⁄4 0:5, and b 1⁄4 1. Insert a title in each subfigure that describes the parameters T
andb. 241 2 335
11. ReadthecontentsofthematrixA1⁄4 4 5 6 rowbyrowandstorethemina
789
vector.
12. Create a function that accepts two complex numbers as input arguments and returns their product and their division.
13. Create a function that accepts two numbers as input arguments and returns one with the larger absolute value. The function must return an error message if the number of arguments is not 2.
14. Create a function that accepts a vector as input argument and returns a. The vector sorted in descending order
b. The number of the vector elements that are zero
c. The elements (in a new vector) that are greater than zero
15. A prime number is a natural number that has exactly two distinct natural number divisors: 1 and itself. The first two prime numbers are 1 and 2. Write a program that finds the prime numbers between 3 and 101. Tip: Use the command rem to check if the remainder of a division is zero.
76 Signals and Systems Laboratory with MATLAB1
16. Suppose that you have a text file with temperature measurements in degrees Fahrenheit. Write a program that reads data from this text file, converts the measurements in degrees Celsius, and stores the converted data in another text file.
17. Solve the following system of algebraic equations: y 1⁄4 1 ” x2 and y 1⁄4 1 þ x.
18. Solve the following system of differential equations: x0(t) 1⁄4 “y(t), y0(t) 1⁄4 “x(t), x(0) 1⁄4 4, y(0) 1⁄4 3. Next, plot the functions x(t) and y(t) in the time interval 0 t 5.