A Practical Introduction to MATLAB - Lecture Notes | CS 682, Lab Reports of Computer Science

Material Type: Lab; Professor: Roch; Class: SPEECH PROCESSING; Subject: Computer Science; University: San Diego State University; Term: Spring 2010;

Typology: Lab Reports

Pre 2010

Uploaded on 03/28/2010

koofers-user-1sh-1
koofers-user-1sh-1 🇺🇸

10 documents

1 / 33

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
A Practical Introduction to Matlab
(Updated for Matlab 5)
Mark S. Gockenbach
Contents
1Introduction 2
2 Simple calculations and graphs 2
2.1 Entering vectors and matrices built-in variables and functions
help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 Arithmetic operations on matrices . . . . . . . . . . . . . . . . . 7
2.3.1 Standard operations . . . . . . . . . . . . . . . . . . . . . 7
2.3.2 Solving matrix equations using matrix division . . . . . . 9
2.3.3 Vectorized functions and operators more on graphs . . . 10
2.4 Some miscellaneous commands . . . . . . . . . . . . . . . . . . . 11
3 Programming in Matlab 13
3.1 Conditionals and loops . . . . . . . . . . . . . . . . . . . . . . . . 14
3.2 Scripts and functions . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.3 A nontrivial example . . . . . . . . . . . . . . . . . . . . . . . . . 17
4 Advanced matrix computations 20
4.1 Eigenvalues and other numerical linear algebra computations . . 20
4.2 Sparse matrix computations . . . . . . . . . . . . . . . . . . . . . 22
4.2.1 Creating a sparse matrix . . . . . . . . . . . . . . . . . . . 22
5 Advanced Graphics 24
5.1 Putting several graphs in one window . . . . . . . . . . . . . . . 24
5.2 3D plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
5.3 Parametric plots . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
6 Solving nonlinear problems in Matlab 28
7 Eciency in Matlab 29
Department of Mathematical Sciences, Michigan Technological University
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21

Partial preview of the text

Download A Practical Introduction to MATLAB - Lecture Notes | CS 682 and more Lab Reports Computer Science in PDF only on Docsity!

A Practical Intro duction to Matlab

Up dated for Matlab 

Mark S Go ckenbach

Contents

Intro duction 

 Simple calculations and graphs   Entering vectors and matrices builtin variables and functions help                                    Graphs                                    Arithmetic op erations on matrices                    Standard op erations                        Solving matrix equations using matrix division         Vectorized functions and op erators more on graphs      Some miscellaneous commands                    

 Programming in Matlab   Conditionals and lo ops                           Scripts and functions                            A nontrivial example                          

 Advanced matrix computations   Eigenvalues and other numerical linear algebra computations    Sparse matrix computations                       Creating a sparse matrix                   

 Advanced Graphics   Putting several graphs in one window                 D plots                                  Parametric plots                            

 Solving nonlinear problems in Matlab 

 E ciency in Matlab 

Department of Mathematical Sciences Michigan Technological University

 Advanced data typ es in Matlab   Structures                                  Cell arrays                                  Ob jects                                 

Intro duction

Matlab Matrix laboratory is an interactive software system for numerical computations and graphics As the name suggests Matlab is esp ecially de signed for matrix computations solving systems of linear equations computing eigenvalues and eigenvectors factoring matrices and so forth In addition it has a variety of graphical capabilities and can b e extended through programs written in its own programming language Many such programs come with the system a numb er of these extend Matlabs capabilities to nonlinear problems such as the solution of initial value problems for ordinary dierential equations Matlab is designed to solve problems numerically that is in niteprecision arithmetic Therefore it pro duces approximate rather than exact solutions and should not b e confused with a symb olic computation system SCS such as Mathematica or Maple It should b e understo o d that this do es not make Matlab b etter or worse than an SCS it is a to ol designed for dierent tasks and is therefore not directly comparable In the following sections I give an intro duction to some of the most use ful features of Matlab I include plenty of examples the b est way to learn to use Matlab is to read this while running Matlab trying the examples and exp erimenting

 Simple calculations and graphs

In this section I will give a quick intro duction to dening numb ers vectors and matrices in Matlab p erforming basic computations with them and creating simple graphs All of these topics will b e revisited in greater depth in later sections

 Entering vectors and matrices builtin variables and

functions help

The basic data typ e in Matlab is an ndimensional array of double precision numb ers Matlab diers from earlier versions of Matlab in that other data typ es are supp orted also in the fact that general multidimensional arrays are supp orted in earlier versions every variable was a twodimensional array matrix with onedimensional arrays vectors and zerodimensional arrays scalars as sp ecial cases The new data typ es include structures much like structures in the C programming languagedata values are stored in named elds classes and cell arrays which are arrays of p ossibly dierent data

 

C 

    whos Name Size Bytes Class

A x  double array C xx  double array a x double array x x  double array

Grand total is  elements using  bytes

Note that the argument  in the cat command indicates that the concatena tion is to o ccur along the third dimension If D and E were k m n arrays the command

catDE

would create a k m n array try it Matlab allows arrays to have complex entries The complex unit i 

p  is represented by either of the builtin variables i or j

sqrt ans    i

This example shows how complex numb ers are displayed in Matlab it also shows that the square ro ot function is a builtin feature The result of the last calculation not assigned to a variable is automatically assigned to the variable ans which can then b e used as any other variable in subsequent computations Here is an example

  ans   sqrtans ans     ans ans    

The arithmetic op erators work as exp ected for scalars A builtin variable that is often useful is  

pi ans  

Ab ove I p ointed out that the square ro ot function is builtin other common scientic functions such as sine cosine tangent exp onential and logarithm are also predened For example

cos sin  ans   exp ans     logans ans  

Other elementary functions such as hyp erb olic and inverse trigonometric func tions are also dened At this p oint rather than providing a comprehensive list of functions avail able in Matlab I want to explain how to get this information from Matlab itself An extensive online help system can b e accessed by commands of the form help commandname For example

help ans

ANS The most recent answer ANS is the variable created automatically when expressions are not assigned to anything else ANSwer

help pi

PI      PI  atan  imaglog      

A go o d place to start is with the command help help which explains how the help systems works as well as some related commands Typing help by itself pro duces a list of topics for which help is available lo oking at this list we nd the entry elfunelementary math functions Typing help elfun pro duces a list of the math functions available We see for example that the inverse tangent function or arctangent is called atan

piatan ans 

It is often useful when entering a matrix to suppress the display this is done by ending the line with a semicolon see the rst example in the next section

1 1.5 2 2.5 3 3.5 4 4.5 5 0

1

2

3

Figure  Another simple Matlab graph

 Arithmetic op erations on matrices

Matlab can p erform the standard arithmetic op erations on matrices vectors and scalars that is on   and dimensional arrays addition subtraction and multiplication In addition Matlab denes a notion of matrix division as well as vectorized op erations All vectorized op erations these include addi tion subtraction and scalar multiplication as explained b elow can b e applied to ndimensional arrays for any value of n but multiplication and division are restricted to matrices and vectors n  

  Standard op erations

If A and B are arrays then Matlab can compute AB and AB when these opera tions are dened For example consider the following commands

A       B         C      whos Name Size Bytes Class

A x  double array

B x  double array C x  double array

Grand total is  elements using  bytes

AB ans    

   AC  Error using   Matrix dimensions must agree

Matrix multiplication is also dened

AC ans       CA  Error using   Inner matrix dimensions must agree

If A is a square matrix and m is a p ositive integer then Am is the pro duct of m factors of A However no notion of multiplication is dened for multidimensional arrays with more than dimensions

C  cat     C      C 

D   D    whos Name Size Bytes Class

C xx  double array D x  double array

   Vectorized functions and op erators more on graphs

Matlab has many commands to create sp ecial matrices the following command creates a row vector whose comp onents increase arithmetically

t   t     

The comp onents can change by nonunit steps

x   x  Columns  through       Columns through     

A negative step is also allowed The command linspace has similar results it creates a vector with linearly spaced entries Sp ecically linspaceabn creates a vector of length n with entries a a  b  a n   a  b  a n       b

linspace  ans  Columns  through       Columns through     

There is a similar command logspace for creating vectors with logarithmically spaced entries

logspace  ans  Columns  through              Columns through        

See help logspace for details A vector with linearly spaced entries can b e regarded as dening a one dimensional grid which is useful for graphing functions To create a graph of y  f x or to b e precise to graph p oints of the form x f x and connect them with line segments one can create a grid in the vector x and then create a vector y with the corresp onding function values It is easy to create the needed vectors to graph a builtin function since Matlab functions are vectorized This means that if a builtin function such as sine is applied to a array the eect is to create a new array of the same size whose entries are the function values of the entries of the original array For example see Figure 

x   pi y  sinx plotxy

0 1 2 3 4 5 6 7 −

−0.

−0.

−0.

−0.

0

1

Figure  Graph of y  sin x

Matlab also provides vectorized arithmetic op erators which are the same as the ordinary op erators preceded by  For example to graph y  x   x^ 

x     y  xx plotxy

the graph is not shown Thus x squares each comp onent of x and xz divides each comp onent of x by the corresp onding comp onent of z Addition and subtraction are p erformed comp onentwise by denition so there are no  or  op erators Note the dierence b etween A and A The rst is only dened if A is a square matrix while the second is dened for any ndimensional array A

 Some miscellaneous commands

An imp ortant op erator in Matlab is the single quote which represents the con jugate transp ose

format long      format long e     e format compact suppresses extra line feeds all of the output in this pap er is in compact format

 xlabelstring ylabelstring lab el the horizontal and vertical axes resp ectively in the current plot  titlestring add a title to the current plot

 axisa b c d change the window on the current graph to a  x  b c  y  d

 grid adds a rectangular grid to the current plot

 hold on freezes the current plot so that subsequent graphs will b e dis played with the current

 hold off releases the current plot the next plot will erase the current b efore displaying

 subplot puts multiple plots in one graphics window

Miscellaneous

 maxx returns the largest entry of x if x is a vector see help max for the result when x is a k dimensional array

 minx analogous to max

 absx returns an array of the same size as x whose entries are the mag nitudes of the entries of x  sizeA returns a  k vector with the numb er of rows columns etc of the k dimensional array A

 lengthx returns the length of the array ie maxsizeA

 save fname saves the current variables to the le named fnamemat  load fname load the variables from the le named fnamemat

 quit exits Matlab

 Programming in Matlab

The capabilities of Matlab can b e extended through programs written in its own programming language It provides the standard constructs such as lo ops and conditionals these constructs can b e used interactively to reduce the tedium of rep etitive tasks or collected in programs stored in mles nothing more than a text le with extension m I will rst discuss the programming mechanisms and then explain how to write programs

 Conditionals and lo ops

Matlab has a standard ifelseifelse conditional for example

t  rand if t  s   elseif t   s   else s  t   end s s 

t t   

The logical op erators in Matlab are      logical equals and  not equal These are binary op erators which return the values and  for scalar arguments

 ans    ans 

 ans 

Thus the general form of the if statement is

if expr statements elseif expr statements    else statements end

The rst blo ck of statements following a nonzero expr executes Matlab provides two typ es of lo ops a forlo op comparable to a Fortran dolo op or a C forlo op and a whilelo op A forlo op rep eats the statements in the lo op as the lo op index takes on the values in a given row vector

Then the sequence of commands

N w  plotsin

pro duces Figure 

−1 0 1 2 3 4 5 6 7

−0.

−0.

−0.

−0.

0

1

Figure  Eect of an mle

As this example shows the commands in the script can refer to the variables already dened in Matlab which are said to b e in the global workspace notice the reference to N and w in plotsinm As I mentioned ab ove the commands in the script are executed exactly as if they had b een typ ed at the keyb oard Much more p owerful than scripts are functions which allow the user to create new Matlab commands A function is dened in an mle that b egins with a line of the following form

function outputoutput  cmd nameinputinput

The rest of the mle consists of ordinary Matlab commands computing the values of the outputs and p erforming other desired actions It is imp ortant to note that when a function is invoked Matlab creates a lo cal workspace The commands in the function cannot refer to variables from the global interactive workspace unless they are passed as inputs By the same token variables created

as the function executes are erased when the execution of the function ends unless they are passed back as outputs Here is a simple example of a function it computes the function f x  sin x^  The following commands should b e stored in the le fcnm the name of the function within Matlab is the name of the mle without the extension

function y  fcnx y  sinx

Note that I used the vectorized op erator  so that the function fcn is also vectorized With this function dened I can now use fcn just as the builtin function sin

x  pipi pi y  sinx z  fcnx plotxyxz grid

The graph is shown in Figure  Notice how plot can b e used to graph two or more functions together The computer will display the curves with dierent line typ esdierent colors on a color monitor or dierent styles eg solid versus dashed on a blackandwhite monitor See help plot for more informa tion Note also the use of the grid command to sup erimp ose a cartesian grid on the graph

 A nontrivial example

Notice from Figure that f x  sin x^  has a ro ot b etween  and of course this ro ot is x 

p   but we feign ignorance for a moment A general algorithm for nonlinear ro otnding is the metho d of bisection which takes a function and an interval on which function changes sign and rep eatedly bisects the interval until the ro ot is trapp ed in a very small interval A function implementing the metho d of bisection illustrates many of the imp ortant techniques of programming in Matlab The rst imp ortant technique without which a useful bisection routine cannot b e written is the ability to pass the name of one function to another function In this case bisect needs to know the name of the function whose ro ot it is to nd This name can b e passed as a string the alternative is to hardco de the name in bisectm which means that each time one wants to use bisect with a dierent function the le bisectm must b e mo died This style of programming is to b e avoided The builtin function feval is needed to evaluate a function whose name is known as a string Thus interactively

fcn ans   

 c  bisectfnabtol   This function locates a root of the function fn on the interval  ab to within a tolerance of tol It is assumed that the function  has opposite signs at a and b

 Evaluate the function at the endpoints and check to see if it  changes sign

fa  fevalfna fb  fevalfnb

if fafb  errorThe function must have opposite signs at a and b end

 The flag done is used to flag the unlikely event that we find  the root exactly before the interval has been sufficiently reduced

done  

 Bisect the interval

c  ab

 Main loop

while absab tol  done

 Evaluate the function at the midpoint

fc  fevalfnc

if fafc   The root is to the left of c b  c fb  fc c  ab elseif fcfb   The root is to the right of c a  c fa  fc c  ab else  We landed on the root done   end

end

Assuming that this le is named bisectm it can b e run as follows

x  bisectfcne  x    sqrtpix ans   e

Not only can new Matlab commands b e created with mles but the help system can b e automatically extended The help command will print the rst comment blo ck from an mle

help bisect

c  bisectfnabtol

This function locates a root of the function fn on the interval ab to within a tolerance of tol It is assumed that the function has opposite signs at a and b

Something that may b e confusing is the use of b oth fn and fn in bisectm I put quotes around fn in the comment blo ck to remind the user that a string must b e passed However the variable fn is a string variable and do es not need quotes in any command line Notice the use of the error function near the b eginning of the program This function displays the string passed to it and exits the mle At the risk of rep eating myself I want to reemphasize a p otentially trouble some p oint In order to execute an mle Matlab must b e able to nd it which means that it must b e found in a directory in Matlabs path The current work ing directory is always on the path to display or change the path use the path command To display or change the working directory use the cd command As usual help will provide more information

 Advanced matrix computations

 Eigenvalues and other numerical linear algebra com

putations

In addition to solving linear systems with the backslash op erator Matlab p erforms many other matrix computations Among the most useful is the com putation of eigenvalues and eigenvectors with the eig command If A is a square matrix then ev  eigA returns the eigenvalues of A in a vector while VD  eigA returns the sp ectral decomp osition of A V is a matrix whose columns are eigenvectors of A while D is a diagonal matrix whose diagonal entries are