1. Trang chủ
  2. » Công Nghệ Thông Tin

MATLAB Primer

33 303 4
Tài liệu đã được kiểm tra trùng lặp

Đ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

Nội dung

CHAPTER 9 MATLAB Primer 9.1 INTRODUCTION MATLAB is a very powerful and well-known software package 1 that is used in science and engineering disciplines, for numerical computation, data analysis, and graphical visualization. It is available in almost all platforms such as personal computers, and workstations running under several operating systems. When you begin a session by typing the command matlab , the first window displayed on the monitor is the command window with the prompt >> , which is waiting for your command. 2 Use the command exit to end the session. MATLAB contains a large collection of built-in functions and commands that are used in an interactive mode, when you are in the command window. As soon as the name of a function or a command is typed at the prompt in the command window, with the proper syntax, the answer is displayed immediately. But there are two other windows, the edit window and graphics window, which will be dis- cussed later. The software package is designed to use additional sets of functions that are more applicable in particular disciplines such as control systems, digital signal processing, communications engineering, and image processing. There are more than 20 sets known as “toolboxes” (e.g., control toolbox, digital signal pro- cessing toolbox, communication toolbox, image processing toolbox). All of them run under MATLAB and implement the functions on the basis of matrix manipu- lation of numerical data, and that is why the software is called MATLAB (matrix laboratory). Simulink is another toolbox that is used to simulate the performance of the systems, when the systems are built by connecting individual blocks rep- resenting different subsystems and the output is obtained when the systems are 1 The software is available from The MathWorks, Inc., 3 Apple Hill Drive, Natick, MA 01760-2098, phone 508-647-7000, fax 508-647-7001, email info@mathworks.com , Website http://www.mathworks.com. 2 If you are logging on a workstation connected to a computer network, you may have to set the proper environment by typing setenv DISPLAY network number: or some other com- mand before launching MATLAB. Introduction to Digital Signal Processing and Filter Design, by B. A. Shenoi Copyright © 2006 John Wiley & Sons, Inc. 391 392 MATLAB PRIMER subjected to different kinds of input signals. MATLAB allows us to construct new functions using the enormous number of built-in functions, commands, and operations in MATLAB and in the many toolboxes, without having to know how to compile, link, load, and create executable code, because MATLAB uses its own language to carry out all these steps, which are invisible to the user. It carries out the steps and gives the answer very fast! In most versions of MATLAB, there is a “symbol” toolbox, which performs does symbolic operations such as differen- tiation, integration, matrix inversion, and solution of differential equations when the operations are expressed in their symbolic form. In more recent versions of this software, new toolboxes such as Filter Design Toolbox and DSP Blockset, which are based on the object-oriented programming features of MATLAB, have been added. These have been treated in some chapters of this book. 9.1.1 Vectors, Arrays, and Matrices Vectors and scalars are special cases of a matrix—all of which are represented as arrays in MATLAB. A scalar is an array of 1 × 1 dimension, whereas a row vector is an array of 1 × n dimension, and a column vector is an array of n × 1 dimension. When elements of an array are typed in a row within square brackets, with a space between the elements, MATLAB displays it as a row vector. For example, when you type >>A=[120315] it displays A=120315 If the array is typed without assigning a name for the array, >>[120315] , MATLAB responds with ans=1 2 0 3 1 5 When you type elements with a semicolon between them, the elements are dis- played in a column vector, for example >>B=[1 2 0; 3 1 5; 0 4 -2] displays the 3 -by-3 matrix B= 1 2 0 31 5 04-2 If a semicolumn is entered at the end of an array or a command, then the array and the output of the command is not displayed on the command window, but the command as well as the output variables are saved in a buffer known as the workspace. The workspace saves the variables, data, contents of arrays and matrices, and other elements as well as a record of the commands typed by the user. It is recommended that at the beginning of the session, you change INTRODUCTION 393 the directory to the disk drive a: if you have one in your computer so that the contents of the workspace are saved in the floppy disk in that drive. Instead of using the semicolumn between the elements, you can type the element on the next line or by leaving one space, type three dots at the end of the line and continue on the next line as shown below; this is useful when the array is very long and extends beyond the end of the line: >>C=[1 2 0 315 0 4 -2] or >>C=[ 1 2 0;315; . 0 4 -2] displays the answer C=1 2 0 31 5 04-2 9.1.2 Matrix Operations It is now obvious that a column vector can be created by typing the elements with a semicolumn separating them or creating a row vector and transposing it. In MATLAB, the transpose of a matrix or a vector is carried out by the operator, that is, the command x’ gives the transpose of the vector or matrix x . Since the vectors and matrices listed and described above have been saved in the workspace, if we type >>A’ ,weget ans 1 2 0 3 1 5 and >>D=C’ yields D= 130 214 05-2 If we type C(:) , we get a column vector with the columns of C arranged in a vertical vector: ans = 1 394 MATLAB PRIMER 3 0 2 1 4 0 5 -2 When a scalar, vector, or matrix is multiplied (or divided) by a scalar c,every element of the scalar, vector or matrix is multiplied (or divided) by c.When c is added to matrix, it is added to every element of the vector or matrix. For example, x=5 ; F=x*C gives the output F=5100 15525 0 20 -10 FF=x+C gives the output as FF=67 5 8610 59 3 Addition and subtraction of two matrices (and vectors) is carried out by MATLAB, according to the rules of matrix algebra, when they have the same dimension. Multiplication of a vector or matrix by a vector or matrix is carried out according to the rules of algebra when they are compatible or commensu- rate for multiplication. The matrix operations and their corresponding notations available in MATLAB are given below: Addition + Subtraction - Multiplication * Power or exponent ^ Transpose ’ Left division \ Right division / Note that the command x=M\b gives us the solution to the equation M*x=b , where M is a square matrix that is assumed to be nonsingular. In matrix algebra, the solution is given by x = M −1 b. The left division is a more commonly used operation in application of matrix algebra. (The command for the right division x=b/M gives the solution to the equation x*M=b , assuming that x and M are compatible for multiplication and the solution in matrix algebra is given by x=bM −1 .) INTRODUCTION 395 When we use the same variables used above but define them with new values, they become the current values for the variables, so we define and use them below as examples of the operations described above: >>A=[1 2 1;0 1 1;2 1 1]; >>B=[2 1 0;1 1 1;-1 2 1]; >>C=A+B C= 331 122 132 >>D=A*B D= 353 032 452 >>M=A; >>b=[2;4;4]; >>x=M\b x = 0.0000 -2.0000 6.0000 Whereas the addition and subtraction of matrices are carried out by the addition and subtraction term by term from the corresponding positions of the elements, we know that the multiplication and “division” of matrices follow different rules. MATLAB gives the correct answer in all the preceding operations. It has another type of operation that is carried out when we use a dot before the sign for the mathematical operation between the two matrices. The multiplication (.*) , divi- sion (./) , and exponentiation (.^) of the terms in the corresponding positions of the two compatible matrices are the three array operations. Instead of multiplying the two matrices as D=A*B , now we type a dot before the sign for multiplication. For example, the answer to >>D=A.*B is D= 220 011 -221 It is easy to see the result of the command >>A ^2 = A ∗ A as ans = 354 222 464 Let us define a matrix X=  12 34  396 MATLAB PRIMER Now we compute U=X.^2 and V=2.^X and get the following outputs: >>U=X.^2 U=  1 2 2 2 3 2 4 2  >>V=2.^X: V=  2 1 2 2 2 3 2 4  A matrix can be expanded by adding new matrices and column or row vectors as illustrated by the following examples: >>F=[A B] F= 121210 011111 211-121 >>b=[5 4 2]; >>G=[A;B;b] G= 121 011 211 210 111 -1 2 1 542 The division operator ./ can be used to divide a scalar by each of the matrix element as shown below, provided there are no zeros in the matrix: >>W = 12./X produces the result W= 12 6 43 >> WW= [6 2; 2 3]; W./WW divides the elements of W by the elements of WW term by term: ans=2 3 21 The element in the (i,j) position of a matrix G is identified by typ- ing >>G(7,2) , and we get ans=4 , and we can change its value by typing >>G(7,2)=6 , so that now we have INTRODUCTION 397 G= 121 011 211 210 111 -1 2 1 562 The colon sign : can be used to extract a submatrix from a matrix as shown by the following examples: >>Q= ⎡ ⎢ ⎣ 256 324 −318 ⎤ ⎥ ⎦ >>Q(:,2) gives a submatrix with elements in all rows and the second column only: ans = 5 2 1 The command Q(3,:) gives the elements in all columns and the third row only: ans = -3 1 8 The command Q(1:2,2:3) gives the elements in the rows from 1 to 2 and in the columns from 2 to 3: ans = 56 24 There are many other operations that can be applied on a matrix, such as A , as listed below: MATRIX OPERATIONS rot90(A) Rotates the matrix array by 90 ◦ fliplr(A) Flips the columns left to right flipud(A) Flips the rows up to down triu(A) Gives the upper triangular part of the matrix tril(A) Gives the lower triangular part of the matrix There are a few special matrices; we will list only three that are often found useful in manipulating matrices: ones(m,n) , which gives a matrix with the number one in all its m rows and n columns 398 MATLAB PRIMER zeros(m,n) , which gives a matrix with zeros in all its m rows and n columns eye(m) , which gives the “identity matrix” of order m × m. We note that the inverse of a matrix A is obtained from the function inv(A) , the determinant of a matrix A is obtained from the function det(A) and the rank from rank(A) . Since this is only a primer on MATLAB, it does not contain all the information on its functions. You should refer to the user’s guide that accompanies every software program mentioned above or any other books on MATLAB [1–3]. When you have logged on to MATLAB or any of the subdirectories for the toolboxes, there is an online help readily available. You type help functionname ,where functionname is the name of the function on which detailed information is desired, and immediately that information is displayed on the command window. So there is no need to memorize the syntax and various features of the function and so on. The best way to learn the use of MATLAB and the toolboxes is to try the functions on the computer, using the help utility if necessary. 9.1.3 Scalar Operations If t = (0.1π) radians per second, the MATLAB function sin(t) gives the answer as 0.3090. To compute and plot v = sin(0.1πt) , in the time interval [0 2π] we have to choose discrete values for the continuous variable t and compute v at these values. To do so, we create an array t=[0.0:0.1:2.0] ; this gives the sequence of 21 values within t = 0.0–2.0 in increments of 0.1. Now if we type the function v=sin(pi*t) , the result is a sequence of 21 values. The command stem(v) immediately plots these values for v in a “graphics window” as shown in Figure 9.1. We have used the command figure to create a new window and the command plot(t,v) to get the plot as a continuous plot joining the discrete values of v (see Fig. 9.2). If we did not use the command figure , the second figure would replace the first one on the graphics window. Typing the command grid on the command window results in the plots having grid lines shown in these figures. Next we use the commands for adding a title and the labels for the y and x coordinates with the commands title, ylabel ,and xlabel . So the commands entered on the command window to get the two figures are as follows. Since MATLAB chooses the scales for the x and y coordinates, depend- ing on the range of their values, we may have to change the literal arguments in the ylabel and xlabel : t = [0.0:0.1:2.0]; v=sin(pi*t); stem(v);grid title(’Values of sin(pi*t)’) ylabel(’Values of sin(pi*t)’) xlabel(’Values of 10t’) figure INTRODUCTION 399 1 0.8 0.6 0.4 0.2 0 −0.2 −0.4 −0.6 −0.8 −1 0 510 15 20 25 Values of sin (pi ∗ t) Plot of sin (pi ∗ t) Values of 10t Figure 9.1 Plot of sin( pi*nT) . 1 Plot of sin (pi ∗ t) 0.8 0.6 0.4 0.2 Values of sin (pi ∗ t) 0 −0.2 −0.4 −0.6 −0.8 −1 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 Values of 10t Figure 9.2 Plot of sin( pi*t ). plot(t,v);grid title(’Plot of sin(pi*t)’) ylabel(’Value of sin(pi*t)’) xlabel(’Value of t’) 400 MATLAB PRIMER 9.1.4 Drawing Plots Additional arguments can be added in the command plot(t,v) to specify the color of the curve; for example, plot(t,v,’g’) will show the curve in green color. The arguments for other colors are as follows: y yellow m magenta c cyan r red b blue w white k black The next argument that can be added is a marker used to draw the curve. For example, plot(t,v,’g’,’+’) will plot the curve with the + sign instead of the line curve, which is the default marker. Other markers that are available are o circle . point * star - solid line : dotted line -- dashed line -.- dash–dot–dash One can plot several curves in the same figure; for example, we can plot both v and y versus t by the command plot(t,v,’g’,’-’t,y,’r’,’*’) . Another way of plotting more than one variable in the same figure is to use the command hold on after plotting the first variable and then typing the command for plotting the second variable: plot(t,v,’g’); hold on plot(t,y,’r’) The use of the MATLAB commands subplot grid ,and axis have been described and used earlier in the book. The commands gtext and ginput are also very useful in plotting. There is a tool called fvtool (filter visualization tool) in the more recent versions of the Signal Processing Toolbox, which offers several other features in plotting the response of digital filters. You may type help gtext , help ginput ,or help fvtool to get more information about them. 9.1.5 MATLAB Functions The other functions, in addition to sin , that are available in MATLAB are given below: [...]... (0:n-1) + 5*(1-odd); 414 MATLAB PRIMER xi = 4*xi.^2; w = besseli(0,beta*sqrt(1-xi/xind))/bes; w = abs([w(n:-1:odd+1) w])’; % [EOF] kaiser.m REFERENCES 1 2 3 4 5 D Hanselman and B Littlefield, Mastering MATLAB 5, Prentice Hall, 1996 The MathWorks, Inc., MATLAB User’s Guide, 1993 D M Etter and D C Kuncicky, Introduction to MATLAB 6, Prentice-Hall, 2002 W J Palm III, Introduction to MATLAB 6 for Engineers,... scripts are done by MATLAB with a higher degree 402 MATLAB PRIMER of precision if and when it is necessary, for example, when we use the functions and scripts in the Signal Processing Toolbox 9.1.7 Control Flow Three functions are used to control the flow of command execution that depend on decisionmaking statements Such functions are found in other programming languages and also in MATLAB They are for... edit the script Note that we can use any of the thousands of functions found in all other toolboxes and in the simulation software called Simulink that runs under MATLAB, which makes this software extremely powerful and versatile 406 MATLAB PRIMER 9.2.1 List of Functions in Signal Processing Toolbox >>help signal Signal Processing Toolbox Version 6.0 (R13) 20-Jun-2002 Filter analysis abs - Magnitude... recursion schurrc - Schur algorithm Multirate signal processing decimate - Resample data at a lower sample rate downsample - Downsample input signal 412 MATLAB PRIMER interp - Resample data at a higher sample rate interp1 - General 1-D interpolation (MATLAB Toolbox) resample - Resample sequence with new sampling rate spline - Cubic spline interpolation upfirdn - Up sample, FIR filter, down sample upsample... syntax and other details, we can type help function But when we have to carry out numerical processing but don’t know the name of the MATLAB function, we may have to go through the list of all MATLAB functions and choose the appropriate one for the purpose The list of all MATLAB functions in the Signal Processing Toolbox is given in Section 9.2.1, and students are encouraged to use the help utility and... waits for the input from the keyboard We may have requests for input for several parameters, and when the data for all the parameters are entered by us from the keyboard, the program is executed 404 MATLAB PRIMER This is helpful when we wish to find the response (output) of the program with different values for the input parameters Similarly, when we add the statement disp(’Values of the parameter xx’)... besselap - Bessel filter prototype buttap - Butterworth filter prototype cheb1ap - Chebyshev Type I filter prototype (passband ripple) cheb2ap - Chebyshev Type II filter prototype (stopband ripple) 408 MATLAB PRIMER ellipap - Elliptic filter prototype Analog filter design besself - Bessel analog filter design butter - Butterworth filter design cheby1 - Chebyshev Type I filter design cheby2 - Chebyshev Type... algorithm hilbert - Discrete-time analytic signal via Hilbert transform idct - Inverse discrete cosine transform ifft - Inverse fast Fourier transform ifft2 - Inverse 2-D fast Fourier transform 410 MATLAB PRIMER Cepstral analysis cceps - Complex cepstrum icceps - Inverse Complex cepstrum rceps - Real cepstrum and minimum phase reconstruction Statistical signal processing and spectral analysis cohere... signal processing They run under MATLAB, which has about 330 functions and operations By typing help function in the command window, where function is the name of these functions, detailed information about them is displayed By typing help signal, we get a complete list of all the functions in the Signal Processing Toolbox, when this has been installed as a subdirectory of the MATLAB directory If we know... convenient procedure So we create a program or a script by clicking File-Open-New-M-file and use a text editor that is built-in MATLAB or any other text editor and save it in the current directory as a file with a name and an m extension We can write this script using the MATLAB functions and operations; we can even use other functions or functions that we have written Such a file is called an M-file, . CHAPTER 9 MATLAB Primer 9.1 INTRODUCTION MATLAB is a very powerful and well-known software package 1. launching MATLAB. Introduction to Digital Signal Processing and Filter Design, by B. A. Shenoi Copyright © 2006 John Wiley & Sons, Inc. 391 392 MATLAB PRIMER

Ngày đăng: 29/09/2013, 21:20

Xem thêm

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN