of {$slidecount} ½ {$title}, {$author} MATLAB The Language of Technical Computing # Keyboard operation Full screen F11 key Next Slide Page down key, Return key Previous Slide Page up key Next Item Single mouse click, Right Arrow key, Space bar Previous Item Left Arrow key First Slide Home key Last Slide End key Font size Use +/- key to increase/decrease font size Miscellaneous C-key: navigates to Table of Content M-key: Mouse navigation on/off P-key: Print mode / Show all Slides S-key: Statusbar off/on # Title Matlab The Language of Technical Computing statistics application #### Haifeng Xu #### (hfxu@yzu.edu.cn) Reference:Kermit Sigmon, MATLAB Primer, Third Edition. Department of Mathematics University of Florida # Table of contents # Basic of Matlab Basic of Matlab Basic commands # Start Matlab ## Start Matlab On most systems, after logging in one can enter MATLAB with the system command matlab and exit MATLAB with the MATLAB command quit or exit. However, your local installation may permit MATLAB to be accessed from a menu or by clicking an icon. # Addition ## Addition Type the following command to add 2 numbers in the command window right after the command prompt >>  >> 13+24  ans = 37  The summand 37 of 13 and 24 is stored in the default variable called ans which is short for answer. # Writing comments ## Writing comments We can write comments in Matlab following the % character.  13+24 % adding using the binary arithmetic operator +  ans = 37  All the characters in a given line that follow the percent character % are ignored by Matlab . It is very helpful to comment what is being done in the code. # Diary file ## Diary file You can create or reopen a diary file in Matlab to record your work. Everything you typed or input and the corresponding output in the command window will be recorded in the diary file. You can create or reopen a diary file by typing diary filename.txt in the command window.  >> diary blah.txt % start a diary file named blah.txt >> 3+56  ans = 59  When you have finished recording, simply type diary off in the command window to turn off the diary file.  >> diary off % turn off the current diary file blah.txt >> type blah.txt % this allows you to see the contents of blah.txt  3+56 ans = 59 diary off   >> diary blah.txt % reopen the existing diary file blah.txt >> 45-54  ans = -9   >> diary off % turn off the current diary file blah.txt again >> type blah.txt % see its contents  3+56 ans = 59 diary off 45-54 ans = -9 diary off  The diary file with .txt extension is simply a text-file. It can be edited in different editors after the diary is turned off in Matlab . To save space in these notes, we suppress the blank lines and excessive line breaks present in Matlab 's command window. get(0,'diary')  # Store values in variables ## Store values in variables Let's learn to store values in variables of our choice. Type the following at the command prompt :  >> VariableCalledX = 12  Matlab stores default value for some variables, such as pi ($\pi$), i and j (complex numbers). >> pi ans = 3.1416 >> i ans = 0 + 1.0000i >> j ans = 0 + 1.0000i  All predefined symbols (variables, constants, function names, operators, etc) in Matlab are written in lower-case. Therefore, it is a good practice to name the variable you define using upper and mixed case letters in order to prevent an unintended overwrite of some predefined Matlab symbol. # Predefined symbols ## Predefined symbols >> pi ans = 3.1416 >> eps ans = 2.2204e-16 >> inf ans = Inf >> NaN ans = NaN >> realmax ans = 1.7977e+308 >> i ans = 0 + 1.0000i >> j ans = 0 + 1.0000i  # Try it ## Evaluate the following expressions in Matlab We can suppress the output on the screen by ending the command with a semi-colon. >> p=45.89*1.00009; % multiplication >> m=5376.0-6.00; % subtraction >> d=89.0/23.3454; % division >> p=2^0.5; % exponentiation >> Sqrt_of_2=2^(1/2) Sqrt_of_2 = 1.4142 >> 2^1/2 ans = 1 >> 10/0 ans = Inf  # Clear the value ## Clear the value We can clear the value we have assigned to a particular variable and reuse it. We demonstrate it by the following commands and their output: >> X=7 X = 7 >> clear X >> X ??? Undefined function or variable 'X'.  Entering X after clearing it gives the above self-explanatory error message preceded by ???. # help or doc command ## help or doc command If you do not understand a Matlab function or command then type help or doc followed by the function or command. For example: >> help sin SIN Sine of argument in radians. SIN(X) is the sine of the elements of X. See also asin, sind. Overloaded methods: codistributed/sin Reference page in Help browser doc sin >> doc sin % this will open Help browser  # Some math commands ## Some math commands Set the variable x to equal 17.13 and evaluate$\cos(x)$,$\log(x)$,$\exp(x)$,$\arccos(x)$,$|x|$,$\text{sign}(x)$using the Matlab commands cos, log, exp, acos, abs, sign, respectively. >> x=17.13; >> cos(x) ans = -0.1482 >> log(x) ans = 2.8408 >> exp(x) ans = 2.7508e+07 >> arccos(x) ??? Undefined function or method 'arccos' for input arguments of type 'double'. >> acos(x) ans = 0 + 3.5331i >> abs(x) ans = 17.1300 >> sign(x) ans = 1  # Format to display floating-point numbers ## Format to display floating-point numbers When we work with real numbers (floating-point numbers) or really large numbers, we might want the output to be displayed in concise notation. This can be controlled in Matlab using the format command with the short or long options with/without e for scientific notation. format compact is used for getting compacted output and format returns the default format. >> format compact >> Y=15; >> Y = Y + acos(-1) Y = 18.1416 >> format short >> Y Y = 18.1416 >> format short e >> Y Y = 1.8142e+001 >> format long >> Y Y = 18.141592653589793 >> format long e >> Y Y = 1.814159265358979e+001 >> format >> Y Y = 18.1416  # M-file ## M-file An M-file is a special text file with a .m extension that contains a set of code or instructions in Matlab. In this course we will be using two types of M-files: script and function files. A script file is simply a list of commands that we want executed and saves us from retyping code modules we are pleased with. A function file allows us to write specific tasks as functions with input and output. These functions can be called from other script files, function files or command window. # Entering matrices ## Entering matrices MATLAB works with essentially only one kind of object — a rectangular numerical matrix with possibly complex entries; all variables represent matrices. In some situations, 1-by-1 matrices are interpreted as scalars and matrices with only one row or one column are interpreted as vectors. ### Matrices can be introduced into MATLAB in several different ways: • Entered by an explicit list of elements, • Generated by built-in statements and functions, • Created in a diskfile with your local editor, • Loaded from external data files or applications. # Entering matrices ## Entering matrices For example, either of the statements A = [1 2 3; 4 5 6; 7 8 9]  and A = [ 1 2 3 4 5 6 7 8 9 ]  creates the obvious 3-by-3 matrix and assigns it to a variable A. >> A = [1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >> A = [ 1 2 3 4 5 6 7 8 9 ] A = 1 2 3 4 5 6 7 8 9  The elements within a row of a matrix may be separated by commas as well as a blank. # Complex numbers ## Complex numbers MATLAB allows complex numbers in all its operations and functions. Two convenient ways to enter complex matrices are: >> A = [1 2;3 4] + i*[5 6;7 8] A = 1.0000 + 5.0000i 2.0000 + 6.0000i 3.0000 + 7.0000i 4.0000 + 8.0000i >> A = [1+5i 2+6i;3+7i 4+8i] A = 1.0000 + 5.0000i 2.0000 + 6.0000i 3.0000 + 7.0000i 4.0000 + 8.0000i  Either i or j may be used as the imaginary unit. If, however, you use i and j as variables and overwrite their values, you may generate a new imaginary unit with, say, ii = sqrt(-1). # How to enter a large matrix ## How to enter a large matrix Listing entries of a large matrix is best done in an ASCII file with your local editor, where errors can be easily corrected. The file should consist of a rectangular array of just the numeric matrix entries. If this file is named, say, data.ext (where .ext is any extension), the MATLAB command load data.ext will read this file to the variable data in your MATLAB workspace. This may also be done with a script file. For example, the file data.ext is  0.2057 0.1123 0.4876 0.0924 0.3164 0.9879 0.3508 0.1249 0.4633 0.8092 0.9211 0.3174 0.6050 0.2238 0.8131 0.3883 0.7844 0.7690 0.0078 0.2176 0.1704 0.6855 0.0244 0.2122 0.7486 0.7947 0.8145 0.3872 0.3736 0.3833 0.5518 0.2916 0.3960 0.4231 0.2510 0.2578 0.2941 0.2902 0.0985 0.1202 0.5774 0.7891 0.1422 0.0875 0.6173 0.2290 0.6035 0.2729 0.6556 0.8929 0.3968 0.5306 0.3175 0.8236 0.5250 0.4400 0.8523 0.0251 0.6401 0.5755 0.6419 0.9644 0.0372 0.7229 0.7032 0.0740 0.8324 0.6537 0.1750 0.3258 0.2576 0.5056 0.4211 0.1806 0.5301 0.4845 0.4325 0.6733 0.5312 0.5557 0.6841 0.5975 0.9569 0.1636 0.5464 0.7519 0.6357 0.1841 0.0451 0.2751 0.1518 0.6948 0.4296 0.1088 0.1844 0.4024 0.3353 0.9357 0.6660 0.3989 0.2287 0.9509 0.7258 0.7232 0.2486 0.7819 0.7581 0.4517 0.6318 0.2120 0.9828 0.2992 0.4579 0.8944 0.4151 0.0642 0.4440 0.3704 0.3474 0.4516 0.1006 0.4326 0.6099 0.1265 0.0773 0.4022 0.4526 0.2405 0.5166 0.1807 0.7673 0.0600 0.8416 0.6606 0.2277 0.2941 0.6555 0.0594 0.1343 0.9138 0.6207 0.4226 0.7639 0.7027 0.2554 0.6712 0.8667 0.7342 0.3839 0.8044 0.2374 0.1098 0.3158 0.0986 0.7067 0.1544 0.3596 0.7593 0.1536 0.0205 0.7152 0.6312 0.5710 0.6273 0.9861 0.5309 0.9338 0.7727 0.1420 0.5578 0.3813 0.5583 0.7406 0.9535 0.9237 0.6421 0.3551 0.1769 0.0216 0.0300 0.0915 0.1875 0.6964 0.1683 0.3134 0.1611 0.7425 0.7437 0.5409 0.6537 0.4190 0.9970 0.9574 0.9106 0.5357 0.4053 0.2662 0.1253 0.1962 0.1662 0.7581 0.4243 0.1059 0.6797 0.9326 0.3908 0.2242 0.2653 0.8006 0.0871 0.1048 0.7978 0.1302 0.3175 0.6225 0.8711 0.4294 0.6816 0.0366 0.1635 0.8161 0.6525 0.9246 0.7458 0.8021  # Generate random matrix ## Generate random matrix The built-in functions rand, magic, and hilb, for example, provide an easy way to create matrices with which to experiment. The command rand(n) will create an$n\times n$matrix with randomly generated entries distributed uniformly between 0 and 1, while rand(m,n) will create an$m\times n$one (m and n denote, of course, positive integers). >> rand(5) ans = 0.6624 0.4116 0.5836 0.3545 0.4134 0.2442 0.6026 0.5118 0.9713 0.2177 0.2955 0.7505 0.0826 0.3464 0.1257 0.6802 0.5835 0.7196 0.8865 0.3089 0.5278 0.5518 0.9962 0.4547 0.7261  # Generate magic matrix ## Generate magic matrix magic(n) will create an integral$n\times n$matrix which is a magic square (rows, columns, and diagonals have common sum); >> magic(3) % sum is 15 ans = 8 1 6 3 5 7 4 9 2 >> magic(5) % sum is 65 ans = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9  For matrix generated by magic(n), the sum is$\frac{n(n^2+1)}{2}$. # Generate Hilbert matrix ## Generate Hilbert matrix hilb(n) is the$n\times n$matrix with elements 1/(i+j-1), which is a famous example of a badly conditioned matrix. It is named Hilbert matrix, the king of ill-conditioned matrices. >> hilb(5) ans = 1.0000 0.5000 0.3333 0.2500 0.2000 0.5000 0.3333 0.2500 0.2000 0.1667 0.3333 0.2500 0.2000 0.1667 0.1429 0.2500 0.2000 0.1667 0.1429 0.1250 0.2000 0.1667 0.1429 0.1250 0.1111  # Generate matrix using for-loop ## Generate matrix using for-loop Matrices can also be generated with a for-loop. For example, the following codes also generate the Hilbert matrix. >> m=5;n=5; >> for i = 1:m for j = 1:n H(i, j) = 1/(i+j-1); end end H H = 1.0000 0.5000 0.3333 0.2500 0.2000 0.5000 0.3333 0.2500 0.2000 0.1667 0.3333 0.2500 0.2000 0.1667 0.1429 0.2500 0.2000 0.1667 0.1429 0.1250 0.2000 0.1667 0.1429 0.1250 0.1111  # Elements of a matrix ## Elements of a matrix Individual matrix and vector entries can be referenced with indices inside parentheses in the usual manner. For example, A(2, 3) denotes the entry in the second row, third column of matrix A and x(3) denotes the third coordinate of vector x. H = 1.0000 0.5000 0.3333 0.2500 0.2000 0.5000 0.3333 0.2500 0.2000 0.1667 0.3333 0.2500 0.2000 0.1667 0.1429 0.2500 0.2000 0.1667 0.1429 0.1250 0.2000 0.1667 0.1429 0.1250 0.1111 >> H(2,3) ans = 0.2500  # Matrix operations ## Matrix operations The following matrix operations are available in MATLAB: Operation Name +addition -subtraction *multiplication ^power 'conjugate transpose \left division /right division These matrix operations apply, of course, to scalars (1-by-1 matrices) as well. # Incompatible for the matrix operation ## Incompatible for the matrix operation If the sizes of the matrices are incompatible for the matrix operation, an error message will result, except in the case of scalar-matrix operations (for addition, subtraction, and division as well as for multiplication) in which case each entry of the matrix is operated on by the scalar. >> A=[1 2 3; 2 3 4; 3 4 5] A = 1 2 3 2 3 4 3 4 5 >> B=[1 2; 3 4] B = 1 2 3 4 >> A*B ??? Error using ==> mtimes Inner matrix dimensions must agree.  # Matrix division ## Left division and right division The “matrix division” operations deserve special comment. If A is an invertible square matrix and b is a compatible column, resp. row, vector, then x = A\b is the solution of A ∗ x = b and, resp., x = b/A is the solution of x ∗ A = b. That is$x = A\backslash b = A^{-1}b$,$x = b/A = bA^{-1}$. In left division, if A is square, then it is factored using Gaussian elimination and these factors are used to solve A ∗ x = b. If A is not square, it is factored using Householder orthogonalization with column pivoting and the factors are used to solve the under- or over- determined system in the least squares sense. Right division is defined in terms of left division by b/A = (A'\b')'. # Array operations ## Array operations The matrix operations of addition and subtraction already operate entry-wise but the other matrix operations given above do not — they are matrix operations. It is important to observe that these other operations, ∗, ^, \, and /, can be made to operate entry-wise by preceding them by a period. For example, either [1,2,3,4].*[1,2,3,4] or [1,2,3,4].^2 will yield [1,4,9,16]. Try it. This is particularly useful when using Matlab graphics. >> [1,2,3,4].*[1,2,3,4] ans = 1 4 9 16 >> [1,2,3,4].^2 ans = 1 4 9 16  # Statements, expressions, and variables ## Statements, expressions, and variables MATLAB is an expression language; the expressions you type are interpreted and evaluated. MATLAB statements are usually of the form variable = expression, or simply expression Expressions are usually composed from operators, functions, and variable names. Evaluation of the expression produces a matrix, which is then displayed on the screen and assigned to the variable for future use. If the variable name and = sign are omitted, a variable ans (for answer) is automatically created to which the result is assigned. # Note that ## MATLAB is case-sensitive MATLAB is case-sensitive in the names of commands, functions, and variables. For example, solveUT is not the same as solveut. ## List the variables currently in the workspace The command who (or whos) will list the variables currently in the workspace. ## Clear variable A variable can be cleared from the workspace with the command clear variablename. The command clear alone will clear all nonpermanent variables. The permanent variable eps (epsilon) gives the machine unit roundoff—about$10^{-16}$on most machines. It is useful in specifying tolerences for convergence of iterative processes. ## Break or stop A runaway display or computation can be stopped on most machines without leaving MATLAB with CTRL-C (CTRL-BREAK on a PC). # Saving a session ## Saving a session When one logs out or exits MATLAB all variables are lost. However, invoking the command save before exiting causes all variables to be written to a non-human-readable diskfile named matlab.mat. When one later reenters MATLAB, the command load will restore the workspace to its former state. # Matrix building functions ## Matrix building functions Convenient matrix building functions are Function Discription eyeidentity matrix zerosmatrix of zeros onesmatrix of ones diagcreate or extract diagonals triuupper triangular part of a matrix trillower triangular part of a matrix randrandomly generated matrix hilbHilbert matrix magicmagic square toeplitzsee help toeplitz >> help triu triu Extract upper triangular part. triu(X) is the upper triangular part of X. triu(X,K) is the elements on and above the K-th diagonal of X. K = 0 is the main diagonal, K > 0 is above the main diagonal and K < 0 is below the main diagonal.  ### Try it >> X=magic(8) X = 64 2 3 61 60 6 7 57 9 55 54 12 13 51 50 16 17 47 46 20 21 43 42 24 40 26 27 37 36 30 31 33 32 34 35 29 28 38 39 25 41 23 22 44 45 19 18 48 49 15 14 52 53 11 10 56 8 58 59 5 4 62 63 1 >> Y=triu(X) Y = 64 2 3 61 60 6 7 57 0 55 54 12 13 51 50 16 0 0 46 20 21 43 42 24 0 0 0 37 36 30 31 33 0 0 0 0 28 38 39 25 0 0 0 0 0 19 18 48 0 0 0 0 0 0 10 56 0 0 0 0 0 0 0 1 >> Z=triu(X,3) Z = 0 0 0 61 60 6 7 57 0 0 0 0 13 51 50 16 0 0 0 0 0 43 42 24 0 0 0 0 0 0 31 33 0 0 0 0 0 0 0 25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 >> W=triu(X,-3) W = 64 2 3 61 60 6 7 57 9 55 54 12 13 51 50 16 17 47 46 20 21 43 42 24 40 26 27 37 36 30 31 33 0 34 35 29 28 38 39 25 0 0 22 44 45 19 18 48 0 0 0 52 53 11 10 56 0 0 0 0 4 62 63 1  # Identity matrix ## Identity matrix eye(m,n) or Y = eye([m n]) returns an$m\times n$matrix with 1's on the diagonal and 0's elsewhere. The size inputs m and n should be nonnegative integers. Negative integers are treated as 0. >> n=3; >> eye(n) % returns the n-by-n identity matrix. ans = 1 0 0 0 1 0 0 0 1 >> eye(3,5) ans = 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 >> eye(5,3) ans = 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 >> eye([5,3]) ans = 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 >> eye([5 3]) ans = 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0  # Matrix of zeros ## Matrix of zeros >> m=5;n=3; >> zeros(m,n) % produces an m-by-n matrix of zeros ans = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 >> zeros(n) % produces an n-by-n one. ans = 0 0 0 0 0 0 0 0 0 >> A=[1 2 3;2 3 4] A = 1 2 3 2 3 4 >> zeros(size(A)) % produces a matrix of zeros having the same size as A ans = 0 0 0 0 0 0  # Create or extract diagonals ## Create or extract diagonals >> x=[1 2 3 4 5] x = 1 2 3 4 5 >> diag(x) ans = 1 0 0 0 0 0 2 0 0 0 0 0 3 0 0 0 0 0 4 0 0 0 0 0 5 >> A=rand(5,5) A = 0.8147 0.0975 0.1576 0.1419 0.6557 0.9058 0.2785 0.9706 0.4218 0.0357 0.1270 0.5469 0.9572 0.9157 0.8491 0.9134 0.9575 0.4854 0.7922 0.9340 0.6324 0.9649 0.8003 0.9595 0.6787 >> diag(A) ans = 0.8147 0.2785 0.9572 0.7922 0.6787 >> diag(diag(A)) ans = 0.8147 0 0 0 0 0 0.2785 0 0 0 0 0 0.9572 0 0 0 0 0 0.7922 0 0 0 0 0 0.6787  # Build matrices from blocks ## Matrices can be built from blocks >> A=rand(3) A = 0.7577 0.6555 0.0318 0.7431 0.1712 0.2769 0.3922 0.7060 0.0462 >> B = [A, zeros(3,2); zeros(2,3), eye(2)] B = 0.7577 0.6555 0.0318 0 0 0.7431 0.1712 0.2769 0 0 0.3922 0.7060 0.0462 0 0 0 0 0 1.0000 0 0 0 0 0 1.0000  # Control flow ## For, while, if — and relations >> n=10; x=[]; >> for i=1:n x=[x,i^2] % add element i^2 to the vector x end x = 1 x = 1 4 x = 1 4 9 x = 1 4 9 16 x = 1 4 9 16 25 x = 1 4 9 16 25 36 x = 1 4 9 16 25 36 49 x = 1 4 9 16 25 36 49 64 x = 1 4 9 16 25 36 49 64 81 x = 1 4 9 16 25 36 49 64 81 100 >> x x = 1 4 9 16 25 36 49 64 81 100  # For ## produce the same vector in reverse order. >> n=10; >> x = []; for i = n:-1:1, x=[x,i^2], end x = 100 x = 100 81 x = 100 81 64 x = 100 81 64 49 x = 100 81 64 49 36 x = 100 81 64 49 36 25 x = 100 81 64 49 36 25 16 x = 100 81 64 49 36 25 16 9 x = 100 81 64 49 36 25 16 9 4 x = 100 81 64 49 36 25 16 9 4 1  # Instead of 1:n ## The for statement permits any matrix to be used instead of 1:n. The variable just consecutively assumes the value of each column of the matrix. For example, >> A=[1 2; 3 4] A = 1 2 3 4 >> s=0;k=0; >> for c=A %c s=s+sum(c); k=k+1; end >> s s = 10 >> k k = 2  NOTE: here c is the collum vector of matrix A. This computes the sum of all entries of the matrix A by adding its column sums. Of course, sum(sum(A)) does it more efficiently; >> A=[1 2 3;4 5 6;7 8 9] A = 1 2 3 4 5 6 7 8 9 >> sum(A) ans = 12 15 18 >> sum(sum(A)) ans = 45  # While ## While The general form of a while loop is while relation statements end  The statements will be repeatedly executed as long as the relation remains true. For example, for a given number$a$, the following will compute and display the smallest nonnegative integer$n$such that$2n ≥ a$: >> n=0;a=100000; >> while 2^n < a n=n+1; end >> n n = 17 >> 2^16 ans = 65536 >> 2^17 ans = 131072  # If ## If The general form of a simple if statement is if relation statements end  The statements will be executed only if the relation is true. Multiple branching is also possible, as is illustrated by >> n=7; >> if n < 0 parity=0; elseif rem(n,2)==0 % rem( , ) : Remainder after division parity=2; else parity=1; end >> parity parity = 1 >> rem(n,2) ans = 1 >> rem(4,2) ans = 0  # Relations ## Relations The relational operators in MATLAB are Operator Discription <less than >greater than <=less than or equal >=greater than or equal ==equal ~=not equal Note that “=” is used in an assignment statement while “==” is used in a relation. Relations may be connected or quantified by the logical operators Logical operator Discription &and |or ~not # Relations ## Relations When applied to scalars, a relation is actually the scalar 1 or 0 depending on whether the relation is true or false. >> 3<5, 3>5, 3==5, 3==3 ans = 1 ans = 0 ans = 0 ans = 1  When applied to matrices of the same size, a relation is a matrix of 0’s and 1’s giving the value of the relation between corresponding entries. >> a=rand(5), b=triu(a), a==b a = 0.9649 0.8003 0.9595 0.6787 0.1712 0.1576 0.1419 0.6557 0.7577 0.7060 0.9706 0.4218 0.0357 0.7431 0.0318 0.9572 0.9157 0.8491 0.3922 0.2769 0.4854 0.7922 0.9340 0.6555 0.0462 b = 0.9649 0.8003 0.9595 0.6787 0.1712 0 0.1419 0.6557 0.7577 0.7060 0 0 0.0357 0.7431 0.0318 0 0 0 0.3922 0.2769 0 0 0 0 0.0462 ans = 1 1 1 1 1 0 1 1 1 1 0 0 1 1 1 0 0 0 1 1 0 0 0 0 1  A relation between matrices is interpreted by while and if to be true if each entry of the relation matrix is nonzero. >> c=(a==b) c = 1 1 1 1 1 0 1 1 1 1 0 0 1 1 1 0 0 0 1 1 0 0 0 0 1 >> if c x=1; else x=0; end >> x x = 0  # Matrices relation ## Matrices relation Hence, if you wish to execute statement when matrices A and B are equal you could type if A == B statement end  but if you wish to execute statement when A and B are not equal, you would type if any(any(A ∼= B)) statement end  or, more simply, if A == B else statement end  Note that the seemingly obvious if A ∼= B, statement, end  will not give what is intended since statement would execute only if each of the corresponding entries of A and B differ. The functions any and all can be creatively used to reduce matrix relations to vectors or scalars. Two any’s are required above since any is a vector operator. # Scalar functions ## Scalar functions Certain MATLAB functions operate essentially on scalars, but operate element-wise when applied to a matrix. The most common such functions are  sin asin exp abs round cos acos log (natural log) sqrt floor tan atan rem (remainder) sign ceil >> a=1;v=[1 2];A=[1 2; 0 1]; >> sin(a) ans = 0.8415 >> sin(v) ans = 0.8415 0.9093 >> sin(A) ans = 0.8415 0.9093 0 0.8415  # Vector functions ## Vector functions Other MATLAB functions operate essentially on a vector (row or column), but act on an m-by-n matrix (m ≥ 2) in a column-by-column fashion to produce a row vector containing the results of their application to each column. Row-by-row action can be obtained by using the transpose; for example, mean(A')'. A few of these functions are  max sum median any min prod mean all sort std For example, the maximum entry in a matrix A is given by max(max(A)) rather than max(A). >> A=rand(3) A = 0.0971 0.3171 0.4387 0.8235 0.9502 0.3816 0.6948 0.0344 0.7655 >> max(A) ans = 0.8235 0.9502 0.7655 >> max(max(A)) ans = 0.9502  # Matrix functions ## Matrix functions Much of MATLAB’s power comes from its matrix functions. The most useful ones are  eig eigenvalues and eigenvectors chol cholesky factorization svd singular value decomposition inv inverse lu LU factorization qr QR factorization hess hessenberg form schur schur decomposition rref reduced row echelon form expm matrix exponential sqrtm matrix square root poly characteristic polynomial det determinant size size norm 1-norm, 2-norm, F-norm, ∞-norm cond condition number in the 2-norm rank rank # Examples ## Examples Let us consider a singular matrix $A=\begin{pmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{pmatrix}$ $|\lambda E-A|=\lambda(\lambda^2-15\lambda-18),$ so, the eigenvalues are $\lambda_1=0,\quad\lambda_2=\frac{15+\sqrt{297}}{2},\quad\lambda_3=\frac{15-\sqrt{297}}{2}.$ Let's check it. >> A=[1 2 3;4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >> det(A) % should be zero ans = 6.661338147750939e-16 >> rank(A) ans = 2 >> eig(A) ans = 16.1168 -1.1168 -0.0000 >> (sqrt(297)+15)/2 ans = 16.1168 >> (-sqrt(297)+15)/2 ans = -1.1168 >> poly(A) ans = 1.0000 -15.0000 -18.0000 -0.0000 >> [U, D]=eig(A) U = -0.2320 -0.7858 0.4082 -0.5253 -0.0868 -0.8165 -0.8187 0.6123 0.4082 D = 16.1168 0 0 0 -1.1168 0 0 0 -0.0000  # Singular value decomposition ## Singular value decomposition If A is positive definite, then R = chol(A) produces an upper triangular R so that R'*R = A. If A is not positive definite, an error message is printed. A = 1 0 0 0 1 0 1 0 1 >> B=A' B = 1 0 1 0 1 0 0 0 1 >> C=A*B C = 1 0 1 0 1 0 1 0 2 >> chol(C) ans = 1 0 1 0 1 0 0 0 1  # Singular value decomposition ## Singular value decomposition In linear algebra, the singular value decomposition (SVD) is a factorization of a real or complex matrix, with many useful applications in signal processing and statistics. Suppose$M$is an$m×n$matrix whose entries come from the field$K$, which is either the field of real numbers or the field of complex numbers. Then there exists a factorization of the form $M=U\Sigma V^*,$ where$U$is an$m×m$unitary matrix over$K$, the matrix$\Sigma$is an$m×n$diagonal matrix with nonnegative real numbers on the diagonal, and$V^*$, an$n×n$unitary matrix over$K$, denotes the conjugate transpose of$V$. Such a factorization is called the singular value decomposition of$M$. The diagonal entries$σ_i$of$Σ$are known as the singular values of$M$. A common convention is to list the singular values in descending order. In this case, the diagonal matrix$Σ$is uniquely determined by$M$(though the matrices$U$and$V$are not). >> A A = 1 2 3 4 5 6 7 8 9 >> svd(A) ans = 16.8481 1.0684 0.0000 >> norm(A) % n = norm(A) returns the largest singular value of A, max(svd(A)). ans = 16.8481  # Submatrices and colon notation ## Submatrices and colon notation Vectors and submatrices are often used in MATLAB to achieve fairly complex data manipulation effects. “Colon notation” (which is used both to generate vectors and reference submatrices) and subscripting by integral vectors are keys to efficient manipulation of these objects. Creative use of these features to vectorize operations permits one to minimize the use of loops (which slows MATLAB) and to make code simple and readable. Special effort should be made to become familiar with them. The expression 1:5 (met earlier in for statements) is actually the row vector [1 2 3 4 5]. The numbers need not be integers nor the increment one. For example, >> 1:5 ans = 1 2 3 4 5 >> 0.2:0.2:1.2 ans = 0.2000 0.4000 0.6000 0.8000 1.0000 1.2000 >> 5:-1:1 ans = 5 4 3 2 1  The following statements will, for example, generate a table of sines. >> x = [0.0:0.1:2.0]' x = 0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000 1.1000 1.2000 1.3000 1.4000 1.5000 1.6000 1.7000 1.8000 1.9000 2.0000 >> y = sin(x) % Note that since sin operates entry-wise, it produces a vector y from the vector x. y = 0 0.0998 0.1987 0.2955 0.3894 0.4794 0.5646 0.6442 0.7174 0.7833 0.8415 0.8912 0.9320 0.9636 0.9854 0.9975 0.9996 0.9917 0.9738 0.9463 0.9093 >> [x y] ans = 0 0 0.1000 0.0998 0.2000 0.1987 0.3000 0.2955 0.4000 0.3894 0.5000 0.4794 0.6000 0.5646 0.7000 0.6442 0.8000 0.7174 0.9000 0.7833 1.0000 0.8415 1.1000 0.8912 1.2000 0.9320 1.3000 0.9636 1.4000 0.9854 1.5000 0.9975 1.6000 0.9996 1.7000 0.9917 1.8000 0.9738 1.9000 0.9463 2.0000 0.9093  # Submatrices of a matrix ## The colon notation can be used to access submatrices of a matrix. >> A=rand(5) A = 0.5678 0.9340 0.3371 0.1656 0.7482 0.0759 0.1299 0.1622 0.6020 0.4505 0.0540 0.5688 0.7943 0.2630 0.0838 0.5308 0.4694 0.3112 0.6541 0.2290 0.7792 0.0119 0.5285 0.6892 0.9133 >> A(1:4,3) % is the column vector consisting of the first four entries of the third column of A. ans = 0.3371 0.1622 0.7943 0.3112 >> A(:,3) % is the third column of A ans = 0.3371 0.1622 0.7943 0.3112 0.5285 >> A(1:4,:) % is the first four rows ans = 0.5678 0.9340 0.3371 0.1656 0.7482 0.0759 0.1299 0.1622 0.6020 0.4505 0.0540 0.5688 0.7943 0.2630 0.0838 0.5308 0.4694 0.3112 0.6541 0.2290 >> A(:,[2 4]) % contains as columns, columns 2 and 4 of A ans = 0.9340 0.1656 0.1299 0.6020 0.5688 0.2630 0.4694 0.6541 0.0119 0.6892 >> B=eye(5) B = 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 >> A(:,[2 4 5])=B(:,1:3)% replaces columns 2,4,5 of A with the first three columns of B. A = 0.5678 1.0000 0.3371 0 0 0.0759 0 0.1622 1.0000 0 0.0540 0 0.7943 0 1.0000 0.5308 0 0.3112 0 0 0.7792 0 0.5285 0 0 >> A(:,[2,4])=A(:,[2,4])*[1 2; 3 4]% Columns 2 and 4 of A can be multiplied on the right by the 2-by-2 matrix A = 0.5678 1.0000 0.3371 2.0000 0 0.0759 3.0000 0.1622 4.0000 0 0.0540 0 0.7943 0 1.0000 0.5308 0 0.3112 0 0 0.7792 0 0.5285 0 0  # fliplr and flipud ## fliplr and flipud B = fliplr(A) returns A with columns flipped in the left-right direction, that is, about a vertical axis. If A is a row vector, then fliplr(A) returns a vector of the same length with the order of its elements reversed. If A is a column vector, then fliplr(A) simply returns A. >> A=[1 2 3; 4 5 6]' A = 1 4 2 5 3 6 >> B=fliplr(A) B = 4 1 5 2 6 3 >> A=[1:5] A = 1 2 3 4 5 >> B=fliplr(A) B = 5 4 3 2 1 >> B=B(5:-1:1) B = 1 2 3 4 5  B = flipud(A) returns A with rows flipped in the up-down direction, that is, about a horizontal axis. If A is a column vector, then flipud(A) returns a vector of the same length with the order of its elements reversed. If A is a row vector, then flipud(A) simply returns A. >> A=[1 2 3; 4 5 6]' A = 1 4 2 5 3 6 >> B=flipud(A) B = 3 6 2 5 1 4 >> A=[1:5]' A = 1 2 3 4 5 >> B=flipud(A) B = 5 4 3 2 1 >> B=B(5:-1:1) B = 1 2 3 4 5  # M-files ## M-files MATLAB can execute a sequence of statements stored in diskfiles. Such files are called “M-files” because they must have the file type of “.m” as the last part of their filename. Much of your work with MATLAB will be in creating and refining M-files. M-files are usually created using your local editor. There are two types of M-files: script files and function files. # Script files ## Script files A script file consists of a sequence of normal MATLAB statements. If the file has the filename, say, rotate.m, then the MATLAB command rotate will cause the statements in the file to be executed. Variables in a script file are global and will change the value of variables of the same name in the environment of the current MATLAB session. Script files may be used to enter data into a large matrix; in such a file, entry errors can be easily corrected. If, for example, one enters in a diskfile data.m A = [ 1 2 3 4 5 6 7 8 ];  then the MATLAB statement data will cause the assignment given in data.m to be carried out. However, it is usually easier to use the MATLAB function load. An M-file can reference other M-files, including referencing itself recursively. # Function files ## Function files provide extensibility to MATLAB You can create new functions specific to your problem which will then have the same status as other MATLAB functions. Variables in a function file are by default local. A variable can, however, be declared global (see help global). We first illustrate with a simple example of a function file. function a = RandInt(m,n) % RANDINT Randomly generated integral matrix. % RandInt(m,n) returns an m-by-n such matrix with entries % between 0 and 9. a = floor(10*rand(m,n));  A more general version of this function is the following: function a = RandInteger(m,n,a,b) % RANDINT Randomly generated integral matrix. % RandInt(m,n) returns an m-by-n such matrix with entries between 0 and 9. % RandInteger(m,n,a,b) return entries between integers a and b. if nargin < 3, a = 0; b = 9; end a = floor((b-a+1)*rand(m,n)) + a;  This should be placed in a diskfile with filename RandInteger.m (corresponding to the function name, It seems that function name can be different from the filename). The first line declares the function name, input arguments, and output arguments; without this line the file would be a script file. Then a MATLAB statement z = RandInt(4,5), for example, will cause the numbers 4 and 5 to be passed to the variables m and n in the function file with the output result being passed out to the variable z. Since variables in a function file are local, their names are independent of those in the current MATLAB environment. Note that use of nargin (“number of input arguments”) permits one to set a default value of an omitted input variable—such as a and b in the example. # Function files ## A function may also have multiple output arguments function [mean, stdev] = stat(x) % STAT Mean and standard deviation % For a vector x, stat(x) returns the mean of x; % [mean, stdev] = stat(x) both the mean and standard deviation. % For a matrix x, stat(x) acts columnwise. [m n] = size(x); if m == 1 m = n; % handle case of a row vector end mean = sum(x)/m; stdev = sqrt(sum(x. 2)/m - mean. 2);  Once this is placed in a diskfile stat.m, a MATLAB command [xm, xd] = stat(x), for example, will assign the mean and standard deviation of the entries in the vector x to xm and xd, respectively. Single assignments can also be made with a function having multiple output arguments. For example, xm = stat(x) (no brackets needed around xm) will assign the mean of x to xm. The % symbol indicates that the rest of the line is a comment; MATLAB will ignore the rest of the line. Moreover, the first few contiguous comment lines, which document the M-file, are available to the on-line help facility and will be displayed if, for example, help stat is entered. Such documentation should always be included in a function file. # Make code efficient ## Make code efficient This function illustrates some of the MATLAB features that can be used to produce efficient code. Note, for example, that x.^2 is the matrix of squares of the entries of x, that sum is a vector function, that sqrt is a scalar function, and that the division in sum(x)/m is a matrix-scalar operation. Thus all operations are vectorized and loops avoided. If you can’t vectorize some computations, you can make your for loops go faster by preallocating any vectors or matrices in which output is stored. For example, by including the second statement below, which uses the function zeros, space for storing E in memory is preallocated. Without this MATLAB must resize E one column larger in each iteration, slowing execution. M = magic(6); E = zeros(6,50); for j = 1:50 E(:,j) = eig(M^i);% note that here i=0+1.0000i end  # More advanced features ## More advanced features Some more advanced features are illustrated by the following function. As noted earlier, some of the input arguments of a function—such as tol in this example, may be made optional through use of nargin (“number of input arguments”). The variable nargout can be similarly used. Note that the fact that a relation is a number (1 when true; 0 when false) is used and that, when while or if evaluates a relation, “nonzero” means “true” and 0 means “false”. Finally, the MATLAB function feval permits one to have as an input variable a string naming another function. (Also see eval.) function [b, steps] = bisect(fun, x, tol) %BISECT Zero of a function of one variable via the bisection method. % bisect(fun,x) returns a zero of the function. fun is a string % containing the name of a real-valued MATLAB function of a % single real variable; ordinarily functions are defined in % M-files. x is a starting guess. The value returned is near % a point where fun changes sign. For example, % bisect(’sin’,3) is pi. Note the quotes around sin. % % An optional third input argument sets a tolerence for the % relative accuracy of the result. The default is eps. % An optional second output argument gives a matrix containing a % trace of the steps; the rows are of form [c f(c)]. % Initialization if nargin < 3, tol = eps; end Trace = (nargout == 2); if x ~= 0, dx = x/20; else, dx = 1/20; end a = x - dx; fa = feval(fun,a); % Execute the specified function. b = x + dx; fb = feval(fun,b); % Find change of sign. while (fa > 0) == (fb > 0) dx = 2.0*dx; a = x - dx; fa = feval(fun,a); if (fa > 0) ~= (fb > 0), break, end b = x + dx; fb = feval(fun,b); end if Trace, steps = [a fa; b fb]; end % Main loop while abs(b - a) > 2.0*tol*max(abs(b),1.0) c = a + 0.5*(b - a); fc = feval(fun,c); if Trace, steps = [steps; [c fc]]; end if (fb > 0) == (fc > 0) b = c; fb = fc; else a = c; fa = fc; end end  # Type functionname ## Type functionname Some of MATLAB’s functions are built-in while others are distributed as M-files. The actual listing of any non-built-in M-file—MATLAB’s or your own—can be viewed with the MATLAB command type functionname. Try entering type eig, type vander, and type rank. >> type eig 'eig' is a built-in function. >> type vander function A = vander(v) %VANDER Vandermonde matrix. % A = VANDER(V) returns the Vandermonde matrix whose columns % are powers of the vector V, that is A(i,j) = v(i)^(n-j). % % Class support for input V: % float: double, single % Copyright 1984-2004 The MathWorks, Inc. %$Revision: 5.9.4.1 Date: 2004/07/05 17:01:29 $n = length(v); v = v(:); A = ones(n,class(v)); for j = n-1:-1:1 A(:,j) = v.*A(:,j+1); end >> type rank function r = rank(A,tol) %RANK Matrix rank. % RANK(A) provides an estimate of the number of linearly % independent rows or columns of a matrix A. % RANK(A,tol) is the number of singular values of A % that are larger than tol. % RANK(A) uses the default tol = max(size(A)) * eps(norm(A)). % % Class support for input A: % float: double, single % Copyright 1984-2007 The MathWorks, Inc. %$Revision: 5.11.4.5 Date: 2007/08/03 21:26:23 \$

s = svd(A);
if nargin==1
tol = max(size(A)) * eps(max(s));
end
r = sum(s > tol);



# End

Thanks very much!

Welcome to my site: www.atzjg.net