Stage 1 MATLAB Self-do-tutorial (Part 1) Contents 1.1 Introduction 1.2 Matrices 1.3 Matrix operations and functions 1.4 Graphics 1.1 Introduction MATLAB is a technical software environment based on matrix manipulations offering both numerical processing and visualization tools. MATLAB combines numerical analysis, matrix-computation, signal processing and visualization tools with a simple user-friendly environment. Problems and solutions are expressed using statements, which resemble standard mathematical expressions without the need for developing software using traditional programming techniques such as C, Pascal or Fortran. The goal of the self-do-tutorial is offering the student with some basic MATLAB knowledge enough for a successful completion of the practices of this course. This means that simplicity has priority over fast execution. Fantasy over creativity. Attainment targets The goals of the Self-do-tutorial are to be able: to generate and manipulate matrices with MATLAB, to visualize results in MATLAB, to write MATLAB m-files. Organization of this chapter The MATLAB introduction is divided into five subsections. Matrices and matrix-functions are discussed in the sections 1.2 and 1.3. A detailed description of MATLAB’s graphical visualization tools is given in Section 1.4 1.2 Matrices MATLAB works with a single object, an matrix, possibly including complex elements. Scalars are treated as matrices, column vectors as matrices and row vectors as matrices. In this section, we shall describe in details how to work with matrices, how to write/read variables and how to select submatrices. __ ___ ___ Generating matrices To declare the (row) vector with, for example, elements 1, 3 and 4, we can type the following: _ >> a = [1 3 4] a = 1 3 4 Another way to declare vectors is to use an arbitrary increment between its elements, for example: >> b = [0:2:6] b = 1 MATLAB 0 2 4 6 or simply: >> b = 0:2:6 b = 0 2 4 6 This results in an integer vector with an increment of 2 between successive elements. The default increment size (if not explicitly given) is 1. The transpose of a matrix or a vector is given by the operation ’, that is, >> a’ ans = 1 3 4 results in the transposed of the vector . Special attention should be given to the fact that the MATLAB operation ’ transposes and complex-conjugates matrices. For transposition only, use the command .’. The last result of any operation that is not saved in a specific variable is kept by MATLAB in the special variable ans. It is possible to generate a column vector by separating the different rows using the semicolon, i.e., _ >> [1; -3; 4] ans = 1 -3 4 Of course we can also define vectors with complex elements, using either or as the imaginary unit. For example: _ _ >> c = [2+i; -i] c = 2.0000 + 1.0000i 0 - 1.0000i but also >> c = [2-j j]’ c = 2.0000 + 1.0000i 0 - 1.0000i Note that the ’ operation not only transposes the vector, but also complex conjugates it. Additionally, one can define a new imaginary unit, for example im unit = sqrt(-1). A matrix is defined in the same way as a vector. This is done by defining either a row vector of columns, or a column consisting of rows, where the different rows are separated by a semicolon, e.g., >> A = [[1 4 7]’ [2 5 8]’ [3 6 9]’] A = 1 2 3 4 5 6 7 8 9 2 MATLAB in ET3502 Stochastic Processes 2004/2005 or >> A = [1 A = 1 2 4 5 7 8 2 3; 4 5 6; 7 8 9] 3 6 9 but also >> A = [[1;4;7] [2;5;8] [3;6;9]]; Note that MATLAB is case sensitive (a A) and that terminating the command line with a semicolon suppresses the display of its result. This feature will become essential when we want to display the final result of complex computations, not being interested in intermediate results. MATLAB includes many built-in functions for automatic matrix creation. Among these are: zeros (matrix with zeros), ones (matrix with ones), eye (identity matrix). __ Submatrices MATLAB allows the selection of specific parts of a vector. For instance, to view only the first three elements of the vector , we can type: _ >> b(1:3) ans = 0 2 4 To view the first and third element, type: >> b([1 3]) ans = 0 4 If we wish to select all the elements beginning at a given position till (and including) the last element, we can use the variable end: >> b(2:end) ans = 2 4 6 Note that the first vector element in MATLAB is indexed 1, and not 0. So, >> b(0) ??? Index exceeds matrix dimensions. This is one of the most common error messages an unexperienced MATLAB user will encounter. Just like vectors, we can select matrix elements, for example the element (1,2) of matrix : _ >> A(1,2) ans = 2 or the first two columns >> A(1:3,1:2) ans = 1 2 3 MATLAB 4 5 7 8 The same result can be achieved by typing: >> A(:,1:2) ans = 1 2 4 5 7 8 Here, the colon means “all elements”. To select the entire matrix, we thus type: >> A(:,:) A = 1 2 3 4 5 6 7 8 9 Variables We can get the list of all currently defined variables using the commands who and whos: >> who Your variables are: A a ans b >> whos Name Size A 3x3 a 1x3 ans 3x2 b 1x4 c 2x1 Grand total is 24 c Bytes Class 72 double 24 double 48 double 32 double 32 double elements using 208 array array array array array (complex) bytes To view the dimension of a specific variable, use the size command, for example: >> size(b) ans = 1 4 It is often sufficient to know only the length of a vector. To do so, use the command length: >> length(b) ans = 4 The clear command clears variables: >> clear c >> who Your variables are: A a ans b When exiting a MATLAB session, all variables are destroyed. However, with the command save it is possible to save all declared variables to the file “matlab.mat” before exiting the session. Later, when starting a new session, one can read these saved variables by typing load. It’s also possible to save only specific variables. For example to save the matrix to a file named “A matrix.mat” type: _ 4 MATLAB in ET3502 Stochastic Processes 2004/2005 >> save A_matrix A This file can be read later with the command: >> load A_matrix If you wish to write data in an ASCII format, use the option -ascii. Use the help function to view other available options of save (help save). We can format an output file with the use of the commands fopen, fprintf and fclose (see the help information of these commands). Writing the vector to a file “a vector.data” using 6 digit notation of which three following the decimal point, we can type: _ >> fp = fopen(’a_vector.data’, ’w’); >> fprintf(fp, ’%6.3f %6.3f %6.3f n’, a(1), a(2), a(3)); >> fclose(fp); _ If fp = 1 (default value), the output will be sent to the standard output (the monitor). 1.3 Matrix operations and functions In this section, we explore different matrix manipulation techniques. Matrix operations As you might have noticed by now, MATLAB uses the standard linear-algebra notation. Both linear and non-linear operations, like addition, subtraction, multiplying, and raising to a power (+,-,* and ^, respectively) can be easily achieved. Pay attention to matrix and vector dimensions. See the following examples: >> A*a ??? Error using ==> * Inner matrix dimensions must agree. >> A*a’ ans = 19 43 67 >> b(2:4)*A ans = 60 72 84 >> a + b([1 2 4]) ans = 1 5 10 It is sometimes desirable to perform element-wise operations. This is done by placing a point before the mathematical symbol. For example, to raise each element of matrix to the power of two, we type: _ >> A.ˆ2 ans = 1 4 9 16 25 36 49 64 81 This is not equivalent to >> Aˆ2 ans = 30 36 42 5 MATLAB 66 81 96 102 126 150 indicating the matrix product Matrix functions MATLAB has many built-in functions. Some (e.g. sin) work on scalars. When called with a matrix argument, those functions will work on each element separately: >> sin(b) ans = 0 0.9093 >> max(sin(b)) ans = 0.9093 -0.7568 -0.2794 In perspective of random variables and stochastic processes functions will be often work on random outcomes of experiments. On generating random numbers simulating outcomes and on analyzing outcomes of experiments. In the following we use the function rand,which generates from a pseudo random number generator a number in the interval (0,1). Each time you use rand your specific answer will be different from ours but must have the same properties: >> rand ans = 0.0153 >> rand ans = 0.7468 >> rand ans = 0.4451 Till now the outcome is shown as the ans. If the value of rand e.g. is compared to a scalar: >> rand>0.5 ans = 1 >> rand>0.5 ans = 0 only the result is presented and we can’t check the quality of the code. This is typical in stochastic environments. If not desired, first a variable can be introduced that holds the generated random number(s): >> y = rand y = 0.4186 >> y > 0.5 ans = 0 Other MATLAB functions work on vectors, but column-wise when called with matrix arguments. An example is the function max, which returns the largest element of a vector: >> rand(1) ans = 0.8381 6 MATLAB in ET3502 Stochastic Processes 2004/2005 >> rand(1,4) ans = 0.9501 0.2311 0.6068 0.4860 >> rand(1,4) ans = 0.8913 0.7621 0.4565 0.0185 0.1763 0.4057 >> max(rand(1,4)) ans = 0.8214 >> X = rand(1,6) X = 0.9218 0.7382 0.9355 0.9169 >> max(x) ??? Undefined function or variable 'x'. >> max(X) ans = 0.9355 >> Y = rand(3,4) Y = 0.4103 0.3529 0.8936 0.8132 0.0579 0.0099 0.1389 0.2028 0.1987 0.6038 0.2722 0.1988 >> max(Y) ans = 0.8936 0.8132 0.2028 0.6038 >> max(Y') ans = 0.6038 0.8936 0.1988 >> max(max(Y')) ans = 0.8936 The most powerful functions in MATLAB are the matrix functions. Examples of such functions are inv which returns the inverse of a matrix, and eig, which returns the eigenvalues and eigenvectors of a matrix. To find out the right way a function should be used, you can use the help command: >> help eig EIG Eigenvalues and eigenvectors. E = EIG(X) is a vector containing the eigenvalues of a square matrix X. [V,D] = EIG(X) produces a diagonal matrix D of eigenvalues and a full matrix V whose columns are the corresponding eigenvectors so that X*V = V*D. [V,D] = EIG(X,’nobalance’) performs the computation with balancing disabled, which sometimes gives more accurate results for certain problems with unusual scaling. 7 MATLAB E = EIG(A,B) is a vector containing the generalized eigenvalues of square matrices A and B. [V,D] = EIG(A,B) produces a diagonal matrix D of generalized eigenvalues and a full matrix V whose columns are the corresponding eigenvectors so that A*V = B*V*D. See also CONDEIG. Overloaded methods help lti/eig.m So, if we want to compute the eigenvalue decomposition , we can type the following: >> [S Lambda] = eig(A); To check that we made no errors, we can execute the following calculation: >> S*Lambda*inv(S) ans = 1.0000 2.0000 4.0000 5.0000 7.0000 8.0000 3.0000 6.0000 9.0000 Due to internal number rounding, the result equals to the matrix only up to a limited accuracy. In this example we have _ >> A - ans ans = 1.0e-014 * 0.0777 0.2665 0.3553 -0.3109 0.0888 0.0888 -0.3997 0 0.3553 Take care when comparing computed results. A test such as >> x == 0 can return a 0 (false), while > abs(x) < 1e-15 can return 1 (true). Rational operators are discussed extensively in Part 2 of this tutorial. MATLAB’s output format can be adjusted with the command format (see help format). If we want to use, for example, a five digit floating-point representation, we type: >> format short e >> ans ans = 7.7716e-16 2.6645e-15 3.5527e-15 -3.1086e-15 8.8818e-16 8.8818e-16 -3.9968e-15 0 3.5527e-15 It is also possible to suppress blank lines in the standard output. To use a mathematical function without knowing its name in MATLAB, we can use the command lookfor. This function searches all m-file help entries for a given string. How such m-files exactly 8 MATLAB in ET3502 Stochastic Processes 2004/2005 look like will be discussed in detail in Part 3 of this tutorial. Assume we want to generate random numbers. To find the corresponding MATLAB function, we can type: >> lookfor 'random numbers' RAND Uniformly distributed random numbers. RANDN Normally distributed random numbers. RANDOM Generates random numbers from a named distribution. and we can choose the one that specifically serves our purposes. Note that if the string contains more than one word we must put quotes (‘.....’) around the string. For an overview of the most important MATLAB functions commands and variables see [1, pp. 22-35]. 1.4 Graphics For the visualization of data we can open a graphical window. The command figure opens such a window and returns a, for each window unique, integer (a so-called “handle”), for example >> h = figure h = 1 Using get(h)we can view the object properties of the figure (like position, dimension, etc.). There are many ways to visualize data. The ones most used are plot for plotting two dimensional data, and surf and mesh for three dimensional plots. See the available help information using the help command. To plot, for example, a number of uniformly distributed outcomes, we can type: >> n = 1:100; >> X = rand(1,100); >> plot(n,X); Furthermore, we can adjust the plotting range and add a grid. >> axis([0 200 -0.1 1.1]); >> grid; in octave use command >> gset grid; Several ways exist for plotting multiple functions at the same time with different colors and line types. We can do this with only one plot statement >> plot(n, X, ’r’, n, X>0.5, ’b’); >> axis([0 200 -0.1 1.1]); or separately using the command hold: >> >> >> >> >> >> >> Y = (X>0.5); plot(X); axis([0 100 -0.1 1.1]); hold on plot(Y, ’r’); Z = Y.*X ; plot(Z, ’g’); In addition, you can generate two plots in different subplots in one figure (above or next to each 9 MATLAB other). To do this, use the command subplot. See the following example. >> >> >> >> >> >> >> >> >> subplot(3,1,1); plot(X); axis([0 100 -0.1 1.1]); subplot(3,1,2); plot(Y); axis([0 100 -0.1 1.1]); subplot(3,1,3); plot(Z); axis([0 100 -0.1 1.1]); If desired, the colors of the subplots can be changed, so can the solid-line presentations. Such a plotting could be: >> >> >> >> >> >> >> >> >> subplot(3,1,1); plot(X, 'bo'); axis([0 100 -0.1 1.1]); subplot(3,1,2); plot(Y, 'r+'); axis([0 100 -0.1 1.1]); subplot(3,1,3); plot(Z, 'gd'); axis([0 100 -0.1 1.1]); 10 MATLAB in ET3502 Stochastic Processes 2004/2005