Tài liệu Real-Time Digital Signal Processing - Appendix B: Introduction of MATLAB for DSP Applications docx

15 606 0
Tài liệu Real-Time Digital Signal Processing - Appendix B: Introduction of MATLAB for DSP Applications docx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Appendix B Introduction of MATLAB for DSP Applications MATLAB (MATrix LABoratory) is an interactive technical computing environment for scientific and engineering applications. It integrates numerical analysis, matrix computation, signal processing, and graphics in an easy-to-use environment. By using its relatively simple programming capability, MATLAB can be easily extended to create new functions. MATLAB is further enhanced by numerous toolboxes such as the Signal Processing Toolbox. The version we use in this book is based on MATLAB for Windows, version 5.1. Several reference books provide a concise tutorial on MATLAB and introduce DSP using MATLAB. However, the best way to learn a new tool is by using it. A useful command for getting started is intro, which covers the basic concepts in the MATLAB language. MATLAB has an extensive on-line help system, which can be used to answer any questions not answered in this appendix. Also, there are many demonstration programs that illustrate various capabilities of MATLAB, which can be viewed by using the command demo. In this appendix, MATLAB is briefly introduced with emphasis on DSP concepts introduced in Chapters 3 and 4. B.1 Elementary Operations This section briefly introduces the MATLAB environment for numerical computation, data analysis, and graphics. B.1.1 Initializing Variables and Vectors The fundamental data-type of MATLAB is array. Vectors, scalars, matrices are handled as special cases of the basic array. A finite-duration sequence can be represented by MATLAB as a row vector. To declare a variable, simply assign it a value at the MATLAB prompt. For example, a sequence xn{2, 4, 6, 3, 1} for n  0, 1, 2, 3, 4 can be represented in MATLAB by two row vectors n and xn as follows: Real-Time Digital Signal Processing. Sen M Kuo, Bob H Lee Copyright # 2001 John Wiley & Sons Ltd ISBNs: 0-470-84137-0 (Hardback); 0-470-84534-1 (Electronic) n  [0, 1, 2, 3, 4]; xn  [2, 4, 6, 3, 1]; Note that the MATLAB command prompt `)' in the command window is ignored throughout this book. The above commands are examples of the MATLAB assignment statement, which consists of a variable name followed by an equal sign and the data values to assign to the variable. The data values are enclosed in brackets, which can be separated by commas and/or blanks. A scalar does not need brackets. For example, Alpha  0.9999; MATLAB statements are case sensitive, for example, Alpha is different from alpha. There is no need to declare variables as integer, real (float or double in C), or complex because MATLAB automatically sets the variables to be real with double precision. The output of every command is displayed on the screen, however, a semi- colon `;' at the end of a command suppresses the screen output, except for graphics and on-line help commands. The xn vector itself is sufficient to represent the sequence x(n), since the time index n is trivial when the sequence begins at n  0. It is important to note that MATLAB assumes all vectors are indexed starting with 1, and thus xn(1)  2, xn(2)  4, and xn(5)  1. We can check individual values of the vector xn. For example, typing xn(3) will display the value of xn (3). MATLAB saves previously typed commands in a buffer. These commands can be recalled with the up-arrow key `4' and down-arrow key `5'. This helps in editing previous commands with different arguments. Terminating a MATLAB session will delete all the variables in the workspace. These variables can be saved for later use by using the MATLAB command save This command saves all variables in the file matlab.mat. These variables can be restored to the workspace using the load command. The command save file_name xn yn will save only selective variables xn and yn in the file named file_name. MATLAB provides an on-line help system accessible by using the help command. For example, to get information about the function save, we can enter the following statement at the command prompt: help save The help command will return the text information on how to use save in the command window. The help command with no arguments will display a list of directories that contains the MATLAB related files. A more general search for informa- tion is provided by lookfor. 454 APPENDIX B: INTRODUCTION OF MATLAB FOR DSP APPLICATIONS B.1.2 Graphics MATLAB provides a variety of sophisticated techniques for presenting and visualizing data as 2D and 3D graphs and annotating these graphs. The most useful command for generating a simple 2D plot is plot(x, y, `options'); where x and y are vectors containing the x- and y-coordinates of points on the graph. The options are optional arguments that specify the color, the line style, which will be discussed later. The data that we plot are usually read from data files or computed in our programs and stored in vectors. For example, to plot the sequence x(n), we can use a simple plot from data stored in two vectors, with vectors n (x-axis) and xn (y-axis) as plot(n,xn); This command produces a graph of xn versus n, a connected plot with straight lines between the data points [n, x(n)]. The outputs of all graphics commands given in the command window are flushed to the separated graphics window. If xn is a vector, plot(xn) produces a linear graph of the elements of xn versus the index of the elements of xn. For a causal sequence, we can use x-vector representation alone as plot(xn); In this case, the plot is generated with the values of the indices of the vector xn used as the n values. The command plot(x,y)generates a line plot that connects the points represented by the vectors x and y with line segments. We can pass a character string as an argument to the plot function in order to specify various line styles, plot symbols, and colors. Table B.1 summarizes the options for lines and marks, and the color options are listed in Table B.2. For example, the following command: plot(x,y,`rÀÀ'); will create a line plot with the red dashed line. Table B.1 Line and mark options Line type Indicator Point type Indicator solid - plus + dashed star * dotted : circle o dash-dot x-mark x ELEMENTARY OPERATIONS 455 Table B.2 Color options Symbol Color y yellow m magenta c cyan r red g green b blue w white k black Plots may be annotated with title, xlabel, and ylabel commands. For example, plot(n, xn); title(`Time-domain signal x(n)'); xlabel(`Time index'); ylabel(`Amplitude'); where title gives the plot with the title `Time-domain signal x(n)', xlabel labels the x-axis with `Time index' and ylabel labels the y-axis with `Amplitude'. Note that these commands can be written in the same line. By default, MATLAB automatically scales the axes to fit the data values. However, we can override this scaling with the axis command. For example, the plot statement followed by axis([xmin xmax ymin ymax]); sets the scaling limits for the x- and y-axes on the current plot. The axis command must follow the plot command to have the desired effect. This command is especially useful when we want to compare curves from different plots using the identical scale. The axis command may be used to zoom-in (or zoom-out) on a particular section of the plot. There are some predefined string-arguments for the axis command. For example, axis(`equal'); sets equal scale on both axes, and axis(`square'); sets the default rectangular graphic frame to a square. The command plot(x,y)assumes that the x and y axes are divided into equally spaced intervals; these plots are called linear plots. The MATLAB commands can also generate a logarithmic scale (base 10) using the following commands: 456 APPENDIX B: INTRODUCTION OF MATLAB FOR DSP APPLICATIONS semilogx(x,y) À using a logarithmic scale for x and a linear scale for y semilogy(x,y) À using a linear scale for x and a logarithmic scale for y loglog(x,y) À using a logarithmic scales for both x and y Generally, we use the linear plot to display a time-domain signal, but we prefer to use the logarithmic scale for y to show the magnitude response in the unit of decibels, which will be discussed in Chapter 4. There are many other specialized graphics functions for 2D plotting. For example, the command stem(n,xn); produces the `lollipop' presentation of the same data. In addition, bar creates a bar graph, contour makes contour plots, hist makes histograms, etc. To compare different vectors by plotting the latter over the former, we can use the command hold on to generate overlay plots. This command freezes the current plot in the graphics window. All subsequent plots generated by the plot command are simply added to the existing plot. To return to normal plotting, use hold off to clear the hold command. When the entire set of data is available, the plot command with multiple arguments can be used to generate an overlay plot. For ex- ample, if we have two sets of data (x1, y1) and (x2, y2), the command plot(x1, y1, x2, y2,`:'); plots (x1, y1) with a solid line and (x2, y2) with a dotted line on the same graph. Multiple plots per window can be done with the MATLAB subplot function. The subplot command allows us to split the graph window into sub-windows. The possible splits can be either two sub-windows or four sub-windows. Two windows can be arranged as either top-and-bottom or left-and-right. The arguments to the subplot(m,n,p) command are three integers m, n,andp. The integer m and n specify that the graph window is to be split into an m-by-n grid of smaller windows, and the digit p specifies the pth window for the current plot. The windows are numbered from left to right, top to bottom. For example, subplot(2,1,1), plot(n), subplot(2,1,2), plot(xn); will split the graph window into a top plot for vector n and a bottom plot for vector xn. B.1.3 Basic Operators MATLAB is an expression language. It interprets and evaluates typed expression. MATLAB statements are frequently of the form variable  expression ELEMENTARY OPERATIONS 457 or simply expression Since MATLAB supports long variable names (up to 19 characters, start with a letter, followed by letters, or digits, or underscores), we should take advantage of this feature to give variables descriptive names. The default operations in MATLAB are matrix (including vector and scalar) opera- tions. The arithmetic operations between two scalars (1Â1 matrix) a and b are: a  b (addition), a À b (subtraction), a*b(multiplication), a/b (division), and a^b (a b ). An array operation is performed element-by-element. Suppose A and B vectors are row vectors with the same number of elements. To generate a new row vector C with values that are the operations of corresponding values in A and B element-by-element, we use A  B, AÀB, A.*B, A./B,andA.^B. For example, x  [1, 2, 3]; y  [4, 5, 6]; then z  x.*y results in z  41018 A period preceding an operator indicates an array or element-by-element operation. For addition and subtraction, array operation and scalar operation are the same. Array (element-by-element) operations apply not only to operations between two vectors of the same size, but also to operations between a scalar and vector. For example, every element in a vector A can be multiplied by a scalar b in MATLAB as B  b*A or B  b.*A. In general, when `point' is used with another arithmetic operator, it modifies that operator's usual matrix definition to a pointwise one. Six relational operators: < (less than), <= (less than or equal), > (greater than), >= (greater than or equal), == (equal), and ~= (not equal), are available for comparing two matrices of equal dimensions. MATLAB compares the pairs of corresponding elements. The result is a matrix of ones and zeros, with one representing `true' and zero represent- ing `false.' In addition, the operators & (AND), | (OR), ~ (NOT), and xor (exclusive OR) are the logical operators. These operators are particularly useful in if statements. For example, if a > b do something end The colon operator `;' is useful for creating index arrays and creating vectors of evenly spaced values. The index range can be generated using a start (initial value), a skip (increment), and an end (final value). Therefore, a regularly spaced vector of numbers is obtained by means of n  [start:skip:end ] Note that no brackets are required if a vector is generated this way. However, brackets are required to force the concatenation of the two vectors. Without the skip para- meter, the default increment is 1. For example, 458 APPENDIX B: INTRODUCTION OF MATLAB FOR DSP APPLICATIONS n  0:2:100; generates the vector n  [024 100], and m  [1:10 20:2:40]; produces the vector m  [12 10 20 22 40]. In DSP application, the vector form of the impulse response hn0:8 n for n  0,1, ,127 can be generated by the commands n  [0:127]; hn  (0.8).^n; where h(n) is stored in the vector hn. We also can use build-in function linspace(start, end, length)instead of colon operator `:'. For example, n  linspace(0,10,6); generates n  [0246810], which is the same as using n  0:2:10; Program flow can be controlled in MATLAB using if statement, while loop, for loop, and switch statement. These are similar to any high-level language such as C, which will be reviewed in Appendix C. Since MATLAB is an interpreted language, certain common programming habits are intrinsically inefficient. The primary one is the use of for loops to perform simple operation over an entire vector. Rather than writing a loop, try to find a vector function or the nested composition of a few vector functions that will accomplish the desired result. For example, the following for-loop: for n  0:127 x(n  1)  sin(2*pi*100/8000*n); end can be replaced by the much efficient vector operation as follows: n  0:127; x  sin(2*pi*100/8000*n); B.1.4 Files MATLAB provides three types of files for storing information: M-files, Mat-files, and Mex-files. M-files are text files, with a `.m' extension. There are two types of M-files: script files and function files. A script file is a user-created file with a sequence of MATLAB commands. The file must be saved with a .m extension. A script file can be executed by typing its name (without extension) at the command prompt in the com- mand window. It is equivalent to typing all the commands stored in the script file at the MATLAB prompt. A script file may contain any number of commands, including those built-in and user-written functions. Script files are useful when we have to repeat a set of commands and functions several times. It is important to note that we should not name a script file the same as the name of a variable in the workspace and the name of a ELEMENTARY OPERATIONS 459 variable it created. In addition, avoid names that clash with built-in functions. We can use any text editor to write, edit, and save M-files. However, MATLAB provides its own text editor. On PC, select New3M-file from the File menu. A new edit window will appear for creating a script file. A function file is also an M-file, just like a script file, except it has a function definition line on the top that defines the input and output explicitly. We will discuss function files later. Mat-files are binary data files with a `.mat' extension. Mat-files are created by MATLAB when we save data with the save command. The data is written in a special format that MATLAB can read. Mat-files can be loaded into MATLAB with the load command. Mex-files are MATLAB callable C programs with .mex extension. We do not use and discuss this type of files in this book. B.2 Generation and Processing of Digital Signals Arithmetic expressions often require computations other than addition, subtraction, multiplication, division, and exponentiation. For examples, many expressions require the use of logarithms, trigonometric functions, etc. MATLAB provides hundreds of built-in functions. With so many available functions, it is important to know how to look for functions and how to use them. Typing help in the command window brings out a list of categories. We can get help on one of these categories by typing the selected category name after help. For example, typing help graph2d gives a list of 2D graphs with a very brief description of each function. Further help can be obtained by typing help followed by the exact name of the function. A set of elementary mathematical functions is listed in the last section. All function names must be in lowercase. As discussed in Chapter 3, a MATLAB function sin (or cos) can be used to generate a digital sinusoidal signal xnA sin2pfnT  f , n  0, 1, , N À 1: B:1 For example, to generate x(n) for A  1.5, f  100 Hz, T  0.001 second (1 ms), f  0:25p, and N  100, we can easily use the following MATLAB script (figb1.m in the software package): n  [0:99]; xn  1.5*sin(2*pi*100*n*0.001+0.25*pi); where the function pi returns the value of p. To view the generated sinewave, we can use plot(n,xn); title(`Sinewave'); xlabel(`Time index'); ylabel(`Amplitude'); The waveform of the generated sinewave is shown in Figure B.1. In Figure B.1, a trivial integer index n is used for the x-axis instead of an actual time index in seconds. To better represent the time-domain signal, we can use the colon operator to generate values between the first and third numbers, using the second number as the increment. For example, if we wish to view x(n) generated in the previous 460 APPENDIX B: INTRODUCTION OF MATLAB FOR DSP APPLICATIONS example with the actual time index t  0, 0.001, , 0.099, we can use the following script (figb2.m in the software package): n  [0:99]; xn  1.5*sin(2*pi*100*n*0.001+0.25*pi); t  [0:0.001:0.099]; plot(t,xn); title(`Sinewave'); xlabel(`Time in second'); ylabel(`Amplitude'); The result is shown in Figure B.2. In addition to these sin, cos, rand, and randn functions discussed in Chapter 3, MATLAB provides many other functions, such as abs(x), log(x), etc. The arguments or parameters of the function are contained in parentheses following the name of the 01020 30 40 50 Time index 60 70 80 90 100 1.5 1.0 0.5 0 Amplitude −0.5 −1.0 −1.5 Figure B.1 Sinewave using integer index 0 0.01 0.02 0.03 0.04 0.05 Time in second 0.06 0.07 0.08 0.09 0.1 1.5 1.0 0.5 0 Amplitude −0.5 −1.0 −1.5 Figure B.2 Sinewave using time index GENERATION AND PROCESSING OF DIGITAL SIGNALS 461 function. If a function contains more than one argument, it is very important to list the arguments in the correct order. Some functions also require that the arguments be in specific units. For example, the trigonometric functions assume that the arguments are in radians. It is possible to nest a sequence of function calls. For example, the following equation: y  X L n1 logjxnj B:2 can be implemented as y  sum(log(abs(xn))); where xn is the vector containing the elements x(n). The built-in functions are optimized for vector operations. Writing efficient MATLAB code (scripts or user-written functions) requires a programming style that generates small functions that are vectorized. The primary way to avoid loops is to use MATLAB functions as often as possible. The details of user-written functions will be presented in Section B.4. Two sequences x 1 n and x 2 n can be added sample-by-sample to form a new sequence ynx 1 nx 2 n: B:3 Adding their corresponding sample sums these two sequences. The summation of two sequences can be implemented in MATLAB by the arithmetic operator `'if sequences are of equal length. For example, we can add a random noise with a sinewave as follows: n  [0:127]; x1n  1.5*sin(2*pi*100*n*0.001+0.25*pi); x2n  1.2*randn(1,128); yn  x1nx2; A given sequence x(n) multiplied by a constant a can be implemented in MATLAB by the scaling operation. For example, ynaxn, where each sample in x(n) is multi- plied by a scalar a  1:5, can be implemented as yn  1.5*xn; Consider the discrete-time linear time-invariant system. Let x(n) be the input sequence and y(n) be the output sequence of the system. If h(n) is the impulse response of the system, the output signal of the system can be expressed as yn X I kÀI xkhn À k X I kÀI hkxn À k: B:4 As discussed in Chapter 3, a digital system is called a causal system if hn0, for n < 0, a digital signal is called a causal signal if x(n)  0 for n < 0. If the sequences x(n) 462 APPENDIX B: INTRODUCTION OF MATLAB FOR DSP APPLICATIONS [...]... Proakis, Digital Signal Processing Using MATLAB V.4, Boston: PWS Publishing, 1997 [3] E W Kamen and B S Heck, Fundamentals of Signals and Systems Using MATLAB, Englewood Cliffs, NJ: Prentice-Hall, 1997 [4] J H McClellan, et al., Computer-Based Exercises for Signal Processing Using MATLAB 5, Englewood Cliffs, NJ: Prentice-Hall, 1998 [5] R Pratap, Getting Started with MATLAB 5, New York: Oxford University... n,yn,`À') , ; 464 APPENDIX B: INTRODUCTION OF MATLAB FOR DSP APPLICATIONS Figure B.3 shows the MATLAB plots of input and output signals Note that the vector a is defined based on coefficients am used in Equation (B.6), which have different signs than the coefficients used in Equation (B.5) An FIR filter can be implemented by setting a ˆ [ 1]or using filter(b,1,x) ; where the vector b consists of FIR filter... individual functions are available in the on-line help facility and the MATLAB Reference Guide Other functions are available in the library of external Mfiles called the MATLAB toolbox such as Signal Processing Toolbox Finally, functions can be developed by individual users for more specialized applications This is an important feature of MATLAB Each user-written function should have a single purpose... with a function definition line, which has a well-defined list of inputs and outputs as follows: function [ output variables]ˆ facction_name(input variables) ; 466 APPENDIX B: INTRODUCTION OF MATLAB FOR DSP APPLICATIONS The function must begin with a line containing the word function, which is followed by the output arguments, an equal sign, and the name of the function The input arguments to the function... deviation sort ± sorting sum ± sum of elements corrcoef ± correlation coefficients cov ± covariance matrix conv ± convolution cov ± covariance deconv ± deconvolution fft ± fast Fourier transform ifft ± inverse fast Fourier transform In addition, the Signal Processing Toolbox provides many additional signal- processing functions References [1] D M Etter, Introduction to MATLAB for Engineers and Scientists,... coefficients bl MATLAB can interface with three different types of data files: Mat-files, ASCII files, and binary files The Mat-file and binary file contain data stored in a memory-efficient binary format, whereas an ASCII file contains information stored in ASCII characters Mat-files are preferable for data that is going to be generated and used by MATLAB programs Data saved in both the Mat-file and ASCII... the ASCII format, we can use a save command with an additional keyword as follows: save out_file yn -ascii; To save data in the binary format, we can use the fwrite command, which writes the elements of an array to the specified file B.4 User-Written Functions As discussed in the previous section, MATLAB has an intensive set of functions Some of the functions are intrinsic (built-in) to the MATLAB itself... many options and outputs The function M-file has very specific rules that are summarized as follows An example of the user-written function dft.m given in Chapter 4 is listed as follows: function [ Xk]ˆ dft(xn, N) % Discrete Fourier transform function % [ Xk]ˆ dft(xn, N) % where xn is the time-domain signal x(n) % N is the length of sequence % Xk is the frequency-domain X(k) nˆ[ 0:1:NÀ1] ; kˆ[ 0:1:NÀ1]... displayed if help is requested for the function name For example, typing help dft will display five comment lines from dft.m M-file on the screen as help information if this M-file is in the current directory These comment lines are usually used to provide a brief explanation, define the function calling sequence, and then a definition of the input and output arguments The only information returned from the.. .DSP APPLICATIONS 463 and h(n) are finite causal sequences, MATLAB has a function called conv(a,b)that computes the convolution between vectors a and b For example, xn ˆ [ 3, 5, 7, 9]; hn ˆ [ 4, 6, 8, 10] 1, 2, ; yn ˆ conv(xn,hn) yn ˆ 2 10 28 60 110 148 160 142 90 B.3 DSP Applications As discussed in Chapter 3, the differential equation of an IIR system can be expressed . search for informa- tion is provided by lookfor. 454 APPENDIX B: INTRODUCTION OF MATLAB FOR DSP APPLICATIONS B.1.2 Graphics MATLAB provides a variety of sophisticated. hn0, for n < 0, a digital signal is called a causal signal if x(n)  0 for n < 0. If the sequences x(n) 462 APPENDIX B: INTRODUCTION OF MATLAB FOR DSP

Ngày đăng: 25/01/2014, 19:20

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan