* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Document
Survey
Document related concepts
Location arithmetic wikipedia , lookup
Law of large numbers wikipedia , lookup
Big O notation wikipedia , lookup
Vincent's theorem wikipedia , lookup
System of polynomial equations wikipedia , lookup
Factorization of polynomials over finite fields wikipedia , lookup
Function (mathematics) wikipedia , lookup
Mathematics of radio engineering wikipedia , lookup
Elementary mathematics wikipedia , lookup
History of the function concept wikipedia , lookup
Function of several real variables wikipedia , lookup
Transcript
2. MATLAB FUNCTIONS 2.1 MATHEMATICAL FUNCTIONS COMMON MATH FUNCTIONS The common math functions include functions to compute the absolute value of a value or the square root of a value or to round a value. We now list these functions, along with brief descriptions. Function Descriptions abs(x) Computes the absolute value of x. sqrt(x) Computes the square root of x. round(x) Rounds x to the nearest integer. fix(x) Rounds (or truncates) x to the nearest integer toward 0. floor(x) Rounds x to the nearest integer toward -∞. ceil(x) Rounds x to the nearest integer toward ∞. sign(x) Returns a value of -1 if x is less then 0, a value of 0 if x equals 0, and a value of 1 otherwise. rem(x,y) Returns the reminder of x /y . For example, rem(25,4) is 1, and rem(100,21) is 16. This function is also called a modulus function. exp(x) Computese^x , wheree is the base for natural logarithms, or approximate ly 2.718282. log(x) Computes ln x, the natural logarithm of x to the base e . log10(x) Computes log10 x, the common logarithm of x to the base 10. round(-2.6) ans = -3 fix(-2.6) ans = -2 floor(-2.6) 24 ans = -3 ceil(-2.6) ans = -2 sign(-2.6) ans = -1 rem(15,2) ans = 1 floor(ceil(10.8)) ans = 11 log10(100) + log10(0.001) ans = -1.0000 abs(-5:5) ans = 5 4 3 2 1 0 1 round([0:0.3:2,1:0.75:4]) ans = 0 0 1 1 1 1 2 2 3 4 5 1 2 3 3 25 4 TRIGONOMETRIC AND HYPERBOLIC FUNCTIONS Trigonometric Functions : The trigonometric functions assume that angles are represented in radians. To convert radians to degrees to radians, use the following conversions, whic h use the fact that 180°= π radians: angle_degrees=angle_radians*(180/pi); angle_radians=angle_degrees*(pi/180); We now list the trigonometric functions with brief descriptions: Function Description Sin(x) Computes the sine of x, where x is in radians. cos(x) Computes the cosine of x, where x is in radians. Tan(x) Computes the tangents of x, where x is in radians. asin(x) Computes the arcsine or inverse sine of x, where x must be between –1 and 1. The function returns an angle in radians between -π/2 and π/2. acos(x) Computes the arccosine or inverse cosine of x, where x must be between -1 and 1. The function returns an angle in radians between 0 and π. atan(x) Computes the arctangent or inverse tangent of x. The function returns an angle in radians between -π/2 and π/2. atan2(y,x) Computes the arctangent or inverse tangent of the value x /y . The function returns an angle in radians that will be between -π and π, depending on the signs of x and y. 26 Hyperbolic Functions : The hyperbolic functions are functions of the natural exponential function, e x ; the inverse hyperbolic functions are functions of the natural logarithm function , ln x . MATLAB includes several hyperbolic functions, as shown in these brief descriptions: Function Description sinh(x) Computes the hyperbolic sine of x, which is equal to cosh(x) tanh(x) asinh(x) e x e x . 2 e x e x Computes the hyperbolic cosine of x, which is equal to . 2 Computes the hyperbolic tangent of x, which is equal to sinh x . cosh x Computes the inverse hyperbolic sine of x, which is equal to ln x x x 2 1 . acosh(x) Computes the inverse hyperbolic cosine of x, which is equal to ln x x 2 1 for x greater than or equal to 1. atanh(x) Computes the inverse hyperbolic tangent of x, which is equal to ln 1 x for x 1 . 1 x Other hyperbolic and inverse hyperbolic functions can be computed using the following equ ations: cosh x for x 0 sinh x 1 1 sec h x , csc h x cosh x sinh x coth x acoth x ln x 1 for x 1 x 1 1 1 x2 asech x ln x for 0 x 1 1 1 x2 acsch x ln x x 27 COMPLEX NUMBER FUNCTIONS Complex numbers are needed to solve many problems in science and engineering. Recall tha t a complex number has the form a ib where is 1 , a is the real part of the value, and b is the imaginary part of the value. MATLAB includes several functions that are specific to complex numbers and their conversi ons: Function conj(x) Description Computes the complex conjugate of the complex number x , Thus, if x i s equal to a ib , then conj(x) will be equal to a ib . real(x) Computes the real portion of the complex number x . imag(x) Computes the imaginary portion of the complex number x . abs(x) Computes the absolute value or magnitude of the complex number x . angle(x) Computes the angle using the value of atan2(imag(x),real(x)); thus, the a ngle value is between -π and π. Polar Plots. Data values are sometimes represented by complex values, which can be considered to be an angle and a magnitude. For example, if we are measuring light intensity around a light source, we might represent the information with an angle from a fixed axis and a magnitude that represents the intensity. To plot complex data, we may want to use a polar plot, as opposed to plotting the magnitude and phase information separately. The MATLAB command for generating a polar plot of the vectors theta and r is the following: Function polar(theta,r) Description Generates a polar of the angles theta (in radians) versus the magnitude r . 28 POLYNOMIAL FUNCTIONS Polynomial Evaluation. There are several ways to evaluate a polynomial for a set of values using MATLAB. To illustrate, consider the following polynomial over the interval[0,5]: g ( x) 3x 4 0.5 x3 x 5.2 Function polyval(a,x) Description Evaluates a polynomial with coefficients a for the values in x, The result is a matrix the same size as x. Polynomials can be also be evaluated using the polyval functions: The following polyval reference will generate and plot 210 points of the polynomial over the desired interval: x=0:5/200:5; a=[3,-0.5,0.1,-5.2]; g=polyval(a,x); plot(x,g),title('Polynomial Function') hold on; set(gcf,'color','w') Polynomial Operations. If we assume that the coefficients of two polynomials are stored in vectors a and b , we can the perform polynomial computations using a and b . Multiplying two polynomials is more complicated than adding or subtracting two polynomials because a number of terms are generated and combined. Similarly, dividing two polynomials is a tedious process because we must multiply and subtract polynomials. MATLAB contains functions to perform polynomial multiplication and division: To illustrate the use of the conv and deconv functions for polynomial multiplication and division, consider the following polynomial product: g ( x) (3x3 5 x 2 6 x 2)( x5 3x 4 x 2 2.5) We can multiply these polynomials using the conv function as shown below: 29 Function Description conv(a,b) Computes a coefficient vector that contains the coefficients of the product of polynomials represented by the coefficients in a and b. The vectors a and b do not have to be the same size. [q,r]=deconv(n,d) Returns two vectors. The first vector contains the coefficients of the quotient and the second vector contains the coefficients of the remainder polynomial. a = [3, -5, 6, -2]; b = [1, 3, 0, -1, 0, 2.5]; g = conv(a,b) g= Columns 1 through 7 3.0000 4.0000 -9.0000 13.0000 -1.0000 1.5000 -10.5000 Columns 8 through 9 15.0000 -5.0000 g represents the following lowing polynomial: g ( x) 3x8 4 x7 9 x6 13x5 x 4 1.5x3 10.5x 2 15x 5 We can illustrate polynomial division using the previous polynomials: h( x ) 3x8 4 x 7 9 x 6 13x5 x 4 1.5 x3 10.5 x 2 15 x 5 x5 3x 4 x 2 2.5 This polynomial division is specified by these commands: g = [3,4,-9,13,-1,1.5,-10.5,15,-5]; b = [1,3,0,-1,0,2.5]; [g,r]=deconv(g,b) g= 3 -5 6 -2 r= 0 0 0 0 0 0 0 0 0 The quotient polynomial is 3 x3 5 x 2 6 x 2 , and the remainder vector contains zeros. 30 Roots Of Polynomials. The solution to many engineering problems involve finding the root s of the an equation of the form y f ( x) where the roots are the values of x for which y is equal to 0. ·The MATLAB function for determining the roots of a polynomial is the roots function: ·If we have the roots of a polynomials and want to determine the coefficients of the polynomial when all the linear terms are multiplied, we can use the poly function: Function Description roots(a) Determines the roots of the polynomial represented by the coefficient vect or a. poly(r) Determines the coefficients of the polynomial whose roots are contained in the vector r. The roots function returns a column vector containing the roots of the polynomial; the number of roots is equal to the degree of the polynomial. To illustrate the use of this function , assume that we want to determine the roots of this polynomial: f ( x) x3 2 x 2 3x 10 The commands to compute and print the roots of this polynomial are p = [1,-2,-3,10]; r = roots(p) r= 2.0000 + 1.0000i 2.0000 - 1.0000i -2.0000 polyval(p,r) ans = 1.0e-013 * -0.0355 + 0.1377i -0.0355 - 0.1377i 0.0711 31 We can verify that these values are roots by evaluating the polynomial at the roots and observing that polynomial values are essentially 0: The output of the function is a row vector containing the polynomial coefficients. For example, we can compute the coefficients of the polynomial with roots -1,1, 3 with the following statement: a( x) ( x 1)( x 1)( x 3) a = poly([-1,1,3]) a= 1 -3 -1 3 The polynomial is x3 3x 2 x 3 32 2.2 FUNCTIONS OF TWO VARIABLES FUNCTION EVALUATION. Recall that evaluating a function of one variable, such as f ( x ) , involves computing a vector of x values, and then computing a corresponding vector of function values as illustrated in these statements: Two-Dimensional Grid : The meshgrid function generates the two matrices that define the underlying grid of for a two dimensional function. Function [x_grid,y_grid]= meshgrid(x,y) Description Generates two matrices of size m times n , based on values in the vecto rs x and y which contain m values and n values, respectively. The x _grid matrix contains the values of x repeated in each now, and y_grid matrix contains the values of y repeated in each column. Thus, to generate the two matrices described on the previous page, we could use the following statements: x = -2:2; y = -1:2; [x_grid,y_grid] = meshgrid(x,y) x_grid = -2 -1 0 1 2 -2 -1 0 1 2 -2 -1 0 1 2 -2 -1 0 1 2 y_grid = -1 -1 -1 -1 -1 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 Once the underlying grid matrices have been defined, we can then compute the corresponding function values. To illustrate, assume that we want to evaluate the following function for the underlying grid defined above: 33 z f ( x, y ) 1 1 x2 y 2 The corresponding function values can be computed and stored in a matrix z with four rows five columns with these statements: z = 1./(1+x_grid.^2 + y_grid.^2) z= 0.1667 0.3333 0.5000 0.3333 0.2000 0.5000 1.0000 0.5000 0.1667 0.3333 0.5000 0.3333 0.1111 0.1667 0.2000 0.1667 0.1667 0.2000 0.1667 0.1111 Since the operations are element-by-element, the value in the z matrix with subscripts(1,1) is computed using the values in x _ grid (1,1) and y _ grid (1,1) , and so on. Mesh Plot : There are several ways to plot a three-dimensional surface with MATLAB. In this discussion we present two types of plots-a mesh plot and a surface plot. A mesh plot has an open mesh as shown in Figure1, and a surface plot has a shaded mesh as Figure2. Several variations of the MATLAB commands for generating these plots are now described: The statements that generated the plots in Figure1 and 2 are these: x = -2:0.1:2; y = -1:0.1:2; [x_grid,y_grid] = meshgrid(x,y); z = 1./(1+x_grid.^2 + y_grid.^2); subplot(2,1,1), mesh(x_grid,y_grid,z),... title('Mesh Plot'),xlabel('x'),... ylabel('y'),zlabel('z'),pause subplot(2,1,2), surf(x_grid,y_grid,z),... title('Surface Plot'),xlabel('x'),... ylabel('y'),zlabel('z') 34 Function Mesh(x_pts,y_pts,z) Description Generates an open mesh plot of the surface defined by the matrix z . The arguments x_pts and y_pts can be vectors defining the ranges of values of the x -and y -coordinates, or they can be matrices defining the underlying grid of x -and y -coordinates. surf(x_pts,y_pts,z) Generates a shaded mesh plot of the surface defined by the matrix z . The arguments x_pts and y_pts can be vectors defining the ranges of values of the x -and y -coordinates, or they can be matrices defining the underlying grid of x -and y –coordinates. After you become comfortable using the mesh and surf commands, use the help function to learn additional options for these command and about the view function (to specify the view point) and the colormap function (to specify color scaling). CONTOUR AND 3-D PLOTS Contour Plots. A Contour map is essentially an elevation map that contains a group of lines that connect-equal elevations. We can think of a line that connects points of equal elevation as a slice of the countryside at that elevation. If we have a map with many lines showing diff erent elevation, we can determine mountains and valleys from it. A contour map is generated form 3-D elevation data, and can be generated by MATLAB using matrices that define the r ange of x - and y -coordinates and the elevation (or z coordinate) data. Two variations of the contour command and a related variation of the mesh command are described below: The following commands generate the plots shown in Figure 3 and 4, assuming that the matr ices x, y, x_grid , y_grid , and z are defined using the previews MATLAB statements: subplot(2,1,1),contour(x,y,z),... title('Contour Plot'),xlabel('x'),... ylabel('y'),grid,pause subplot(2,1,2),meshc(x_grid,y_grid,z),... title('Mesh/Contour Plot'),xlabel('x'),... ylabel('y'),zlabel('z') 35 Labeling Contours : Each contour level has a value associated with it. clabel uses these val ues to display labels for 2-D contour lines. The contour matrix contains the values clabel use s for the labels. This matrix is returned by contour. contour3, and contourf. clabel optionally returns the handles of the Text objects used as label. You can then use thes e handles to set the properties of the label string. Function Description Clabel Generates labels using the contour matrix and displays the labels in the current Figure. contour(x,y,z) Generates a contour plot of the surface defined by the matrix z . The arguments x and y are vectors defining the ranges of values of the x -and y -coordinates. The number of contour lines and their values are chosen automatically. contour(x,y,z,v) Generates a contour plot of the surface defined by the matrix z . The arguments x and y are vectors defining the ranges of values of the x -and y -coordinates. The vector v defines the values to use for the contour lines. contour3 Display 3-D isolines generated form values given by a matrix z . contourf Displays a 2-D contour plot and fills the area between the isoline s with a solid color. meshc(x_pts,y_pts,z) Generates an open mesh plot of the surface defined by the matrix z . The arguments x_pts and y_pts are vectors defining the ranges of values of the x -and y -coordinates, or they can be matrices defining the underlying grid of x -and y -coordinates. In addition, a contour plot is generated below the mesh plot. 36 z = peaks; [c,h] = contour(z,10); clabel(c,h); title('Contour Labeled Using-clabel(c,h)') The 'manual' option enables you to add labels by selecting the contour you want to label with the mouse. You can also use this option to label only those contours you select interactively. For example, clabel(c,h,'manual') displays a crosshair cursor when your cursor is inside the Figure. Pressing any mouse button labels the contour line closest to the center of the crosshair. Filled Contours : contourf displays a two-dimensional contour plot and fills the areas between contour lines. Use the caxis function to control the mapping of contour to color. For example, this filled contour plot of the peaks data uses caxis to map the fill colors into the center of the colormap. z = peaks; [c,h] = contourf(z,10); caxis([-20 20]) title('Filled Contour Plot Using-contourf(z,10)') 37 Pcolor Pseudocolor (Checkerboard) Plot. pcolor(c) is a pseudocolor or "checkerboard" plot of matrix c. Function Description pcolor(c) The values of the elements of c specify the color in each cell of the plot. In the default shading mode, 'faceted', each cell has a constant color and the last row and column of c are not used. With shading('interp'), each cell has color resulting from bilinear interpolation of the color at its four vertices and all elements of c are used. The smallest and largest elements of c are assigned the first and last colors given in the color table; colors for the remainder of the elements in c are determined by table-lookup within the remainder of the color table. pcolor(x,y,c) where x and y are vectors or matrices, makes a pseudocolor plot on the grid defined by x and y. pcolor is really a surf with its view set to directly above. pcolor returns a handle to a surface object. z = peaks; pcolor(z); z = peaks; pcolor(z); title('pcolor(z)') shading interp title('pcolor(z)-shading interp') 38 Colorbar Display Color Bar (Color Scale). Function Description colorbar('vert') This Function appends a vertical color scale to the current axis. colorbar('horiz') This Function appends a horizontal color scale. colorbar(h) places the colorbar in the axes h. The colorbar will be horizontal if the axes h width > height (in pixels). colorbar without arguments either adds a new vertical color scale or updates an existing colorbar. h = colorbar(...) returns a handle to the colorbar axis. z = peaks; z = peaks; pcolor(z); shading interp pcolor(z); shading interp colorbar('vert') title('colorbar(vert)') colorbar('horiz') title('colorbar(horiz)') 39 EXAMPLE : CONTOUR, PCOLOR MATLAB Program File : 'exam3.m' fid1=fopen('exam.dat','r'); fid2=fopen('exam.out','w'); ni=fscanf(fid1,'%g',[1 1]);nj=fscanf(fid1,'%g',[1 1]); a=fscanf(fid1,'%g',[ni nj]);b=fscanf(fid1,'%g',[ni nj]); c=a.*b; d=a*b; fprintf(fid2,'%4.1f %4.1f %4.1f \n',c); fprintf(fid2,'%4.1f %4.1f %4.1f \n',d); pcolor(d);shading interp;han=colorbar('vert'); hold on [c,h]=contour(c,9:25);clabel(c); xlabel('row');ylabel('col');title('Matrix Product'); status=fclose('all'); 40 3-D PLOT Function plot3(x,y,z) Description Generates a line in 3-D through the points whose coordinates are the elements ofrm bold x ,rm bold y , andrm bold z and then produces a 2 -D projection of that line on the screen. t = 0:pi/50:10*pi; plot3(sin(t),cos(t),t) title('Plot3') set(gcf,'color','w') 41 2.3 RANDOM NUMBER GENERATING FUNCTIONS UNIFORM RANDOM NUMBERS Random numbers are not defined by an equation; instead they can be characterized by the distribution of values. For example, random numbers that are equally likely to be any value between an upper and lower limit are called uniform random numbers. The rand function in MATLAB generates random numbers uniformly distributed over the interval [0,1]. A seed value is used to initiate a random sequence of value; this seed value is initially set to 0, but it can be changed with the seed function. The rand function generates the same sequence of random values in each work session if the same seed value is used. The following command generate and print two sets of ten random Function Description rand(n) Generates an n n matrix containing random numbers between 0 and 1. rand(m,n) Generates an m n matrix containing random numbers between 0 and 1. rand('seed',n) Sets the value of the seed n . rand('seed') Returns the current value of the random number generator seed. numbers uniformly distributed between 0 and 1; the difference between the two sets is caused by the different seeds: rand('seed',0) set1=rand(10,1); rand('seed',123) set2=rand(10,1); [set1 set2] ans = 0.2190 0.0878 0.0470 0.6395 0.6789 0.0986 0.6793 0.6906 0.9347 0.3415 0.3835 0.2359 0.5194 0.2641 42 0.8310 0.6044 0.0346 0.4181 0.0535 0.1363 Random sequences with values that range between values other than 0 and 1 are often needed. To illustrate, suppose that we want to generate values between -5 and 5. We first generate a random number r (which is between 0 and 1), and then multiply it by 10 , which is the difference between the upper and lower bounds(5 -(-5)). We then add the lower bound (-5), giving a resulting value that is equally likely to be any value between -5 and 5. Thus, if we want to convert a value r that is uniformly distributed between 0 and 1 to a value uniformly distributed between a lower bound a and an upper bound b , we use the following equation: x (b a ) r a data_1 = 2 * rand(1,500)+2; plot(data_1) hold on axis([0 500 0 6]); grid on title('Random Number-data _1') set(gcf,'color','w') 43 GAUSSIAN RANDOM NUMBERS MATLAB will generate Gaussian values with a mean of zero and a variance of 1.0 if we specify a normal distribution. The functions for generating Gaussian values are as following: Function Description randn(n) Generates an n n matrix containing Gaussian (or normal) rando m numbers with a mean of 0 and a variance of 1. randn(m,n) Generates an m n matrix containing Gaussian (or normal) rando m numbers with a mean of 0 and a variance of 1. data_2 = randn(1,500)+3; plot(data_2) hold on axis([0 500 0 6]) title('Random Number-data _2') xlabel('index, k') set(gcf,'color','w') 44