Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 1 MATLAB BASICS & PROGRAMMING Dr. N. YADAIAH Associate professor Dept. of Electrical & Electronics Engineering J N T University, College of Engineering, HYDERABAD
[email protected] Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 2 MATLAB BASICS What Is MATLAB? • MATLAB® is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation. • The name MATLAB stands for MATrix LABoratory. • Matlab is a case sensitive. Typical uses include o Math and computation o Algorithm development o Data acquisition Modeling, simulation, and prototyping o Data analysis, exploration, and visualization o Scientific and engineering graphics o Application development, including graphical user interface building • MATLAB is an interactive system whose basic data element is an array that does not require dimensioning. • In Academic environment, it is the standard instructional tool for introductory and advanced courses in mathematics, engineering, and science. • In Industry, MATLAB is the tool of choice for high-productivity research, development, and analysis. • MATLAB features a family of add-on application-specific solutions called toolboxes. Very important to most users of MATLAB, toolboxes allow us to learn and apply specialized technology. • Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the MATLAB environment to solve particular classes of problems. • Areas in which toolboxes are available include signal processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and many others. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 3 The MATLAB System The MATLAB system consists of five main parts: Development Environment: This is the set of tools and facilities that help us to use MATLAB functions and files. Many of these tools are graphical user interfaces. It includes the MATLAB desktop and Command Window, a command history, an editor and debugger, and browsers for viewing help, the workspace, files, and the search path. The MATLAB Mathematical Function Library: This is a vast collection of computational algorithms ranging from elementary functions like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms. The MATLAB Language: This is a high-level matrix/array language with control flow statements, functions, data structures, input/output, and object-oriented programming features. Graphics: MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs. It includes high-level functions for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. It also includes low-level functions that allow you to fully customize the appearance of graphics as well as to build complete graphical user interfaces on your MATLAB applications. The MATLAB Application Program Interface (API). This is a library that allows us to write C and Fortran programs that interact with MATLAB. It includes facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 4 Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 5 General Commands one should remember Help Commands help lists topics on which help is available. helpwin opens the interactive help window. helpdesk opens the web browser based help facility. help topic provides help on topic. lookfor string lists help topics containing string. demo runs the demo program. Info Info about MATALB ver MATLAB version info. Start & Exit matlabrc Master startup file startup M-file executed at startup quit Quit MATLAB exit Same as quit. Variable and Workspace information who lists variables currently in the workspace. whos lists variables currently in the workspace with their size. what lists m-, mat-, and mex-files on the disk./List files in the directory. whatsnew Display ReadMe files. which Locate a file clear clears the workspace, all variables are removed. clear x y z clears only variables x, y and z. clear all clears all variables and functions from workspace. mlock fun locks function fun so that clear cannot remove it. munlock fun unlocks function fun so that clear can remove it. clc clears command window, command history is lost. home same as clc. clf clears figure window. echo Echo commands in script file. load Load variables from file. save Save variables in MAT – file. length Length of a vector. size size of a matrix. pack Consolidate memory space disp Display text or matrix. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 6 Directory information pwd shows the current working directory. cd changes the current working directory. dir lists contents of the current directory. ls lists contents of the current directory, same as air. path gets or sets MATLAB se~rch path. editpath modifies MATLAB search path. copyfile copies a file. mkdir creates a directory. ↑ ↓ Recall previous commands. delete Delete file dairy Save text of MATLAB session type Show contents of file ! Access operating system General information computer tells you the computer type you are using clock gives you wall clock time and date as a vector. date tells you the date as a string. more controls the paged output according to the screen size. ver gives the license and the version information about MATLAB installed on your computer. bench benchmarks your computer on running MATLAB. compared to other computers. cputime Elapsed CPU time. etime Elapsed time function tic Start stopwatch timer toc Read stopwatch timer Punctuation Marks and Other Symbols , Comma: A comma is used to: • separate variables in the input and output list of a function, Example: [t ,x] = ode23 ( 'pend' ,to ,tf ,x0), • separate the row and column indices in a matrix, Example: A(m,n), A(l: 10,3) etc., • separate different commands on the same line. Example: plot(x, y) , grid, xlabel('x') etc. ; Semicolon: A semicolon is used to: • suppress the MATLAB' output of a command, Example: x=1:10 ; y= A*x; etc., Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 7 • separate rows in the input list of a matrix. Example: A= [1 2; 4 9]. : Colon: A colon is used to specify range: • in creating vectors, Example: x=l: 10; y=.l:2: 100; etc. • for matrix and vector indices, • in for loops. Example: for i=l: 20, x=x+i; end. ` Right Quote: A single right quote is used to transpose a vector or a matrix. Example: symA = (A' +A) /2. ` ‘ Single Quotes: A pair of single right quote characters is used to enclose a character string. .Example: xlabel('time'), title('My plot') etc. . Period: A period is used: • as a decimal point, i, • in array operations. Example: Asq = A.^ 2 . . Two periods: Two periods are used in cd . . command to access parent directory. ... Ellipsis: Ellipsis (three periods) at the end of a command denotes continuation to the next line. Exampte: x = [log(1:100) sin(v+a.*b) 22.3 23.0 . . . 34.0 33.0 40:50 80]; ! Exclamation: An exclamation preceding a command is used to send the local operating system command command to the system. This command is not applicable to Macs. Example: ! emacs newfile .m invokes the local emacs editor. % Percent: A percent character is used to: • used to mark the beginning of a comment, except when used in character strings. Example: % This is a comment, but rate = ‘8.5%’ is a string. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 8 • .to denote formats in standard I/O functions sprintf and fprintf. Example: sprintf('R = %6.4f', r). ( ) Parentheses: Parentheses are used to: • .specify precedence in arithmetic operations, Example: a = 5/ (2+x* (3-i)); etc. • .enclose matrix and vector indices, Example: A(1:5, 2) = 5; v = x(1: n-5); etc. • enclose the list of input variables of a function. Example: [t,x]=ode23('pend', to, tf, x0). ., [ ] Square brackets: Square brackets are used to: • form and concatenate vectors and matrices, Example: v = [1 2 3:9]; X = [v; log(v)]; etc. • enclose the list of output variables of a function. Example: [V,D] = eig(A); etc. Special Variables and Constants Constants pi π (= 3.14159...) inf ∞ (infinity) NaN Not-a-Number i, j Imaginary unit ( 1 − ) eps Machine precision. realmax Largest real number. realmin Smallest real number. Variables ans Default output variable. nargin Number of input arguments. nargout Number of output arguments. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 9 Working with Files and Directories MATLAB WINDOWS: Once the program starts, the window that opens, shown below, contains three smaller windows, which are: the Command Window, the Workspace Window, and the Command History Window. • The above three windows contains eight different windows in MATLAB. S.No. Name of Window Purpose 1 Command Window Main window, enters variables, runs programs. 2 Figure Window Contains output from graphic commands. 3 Editor Window Creates and debugs script and function files. 4 Help Window Provides help information. 5 Launch Pad Window Provides access to tools, demos, and documentation. 6 Command History Window Logs commands entered in the command window. 7 Workspace Window Provides information about the variables that are used. 8 Current Directory Window Shows the files in the current directory. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 10 Where are you ? This information is available in three ways: 1. Look at the command window toolbar. There is small window that show the name of the current directory along with its path. For example, the below Fig.1 shows that the current directory is D:\Matlab6\work. 2. We can get the same information from the command line by typing pwd (Present Working Directory). 3. The current directory is also displayed in a separate subwindow to the left of the command window. If it is not visible, click on the Current Directory tab. Fig 1. Which directory are you in ? Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 11 • The required window can be selected by choosing appropriate name of the window in VIEW as below: How to change the current directory? The current directory can be changed with the cd DirectoryName command on the command line. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 12 What are the contents of the current directory? The contents of the current directory in the current directory subwindow (below figure) or by typing dir or ls on the command line. Fig. 2. Current directory information from the MATLAB desktop. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 13 What is the MATLAB path? MATLAB path is a variable, stored under the name path that contains the paths of all directories that are automatically included in MATLAB’s search path. But default, all directories that are installed by the MATLAB installer are included in this path. The user path can be set by the following procedure: Step 1: Step 2: Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 14 or Also it can be set in command window by using addpath function: addpath(‘D:\presentation\matlab_presentation’); This can be verified in current directory of matlab toolbar as: • So far we have talked about how to access the MATLAB and its features. • As we know that, in any programming language is consists of: (i) Data types (ii) Algebraic and logical operators. (iii) Mathematical relations. (iv) Control statements (v) Input and output accessing (vi) Functions and subprograms. The MATLAB is very big package and but, it is almost equal to a language. We now discuss the major features of programming language with MATLAB. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 15 Creating, Saving, and Executing a Script File • A Script File is a user-created file with a sequence of MATALB commands in it. • The file must be saved with a ‘.m’ extension to its name, thereby, making it an M-file. • A script file is executed by typing its name at the command prompt. Method: 1. Create a new file: 2. Type the code 3. Write & save with suitable name with .m extension. 4. Now go back to MATLAB command prompt and type the file without .m to run. Creating and Executing a Function File • A Function File is also an M-file, just like a script file, except it has a function definition line on the top that defines the input and output explicitly. Method: 1 Create a new file: 2 Type the code 3 Write & save with suitable name with .m extension. 4 Now go back to MATLAB command prompt and type the file without .m to run. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 16 Data Types There are 14 fundamental data types (or classes) in MATLAB. Each of these data types is in the form of an array. This array is a minimum of 0-by-0 in size and can grow to an n-dimensional array of any size. Two-dimensional versions of these arrays are called matrices. The char data type holds characters in Unicode representation. A character string is merely a 1-by-n array of characters. To hold an array of strings of unequal length, use a cell array. Numeric data types include signed and unsigned integers, single- and double- precision floating point, and sparse matrices of double-precision. The following hold true for numeric data types in MATLAB: All MATLAB computations are done in double-precision. Integer and single precision arrays offer more memory efficient storage than double-precision. All data types support basic array operations, such as subscripting and reshaping. To perform mathematical operations on integer or single precision arrays, it must convert them to double precision using the double function. A cell array provides a storage mechanism for dissimilar kinds of data. For example, you can store a 1-by-50 char array, a 7-by-13 double array, and a 1-by- 1 uint32 in cells of the same cell array. The MATLAB structure data type is similar to the cell array in that it also stores dissimilar kinds of data. But, in this case, it stores the data in named fields rather than in cells. MATLAB data types are implemented as classes. We can also create MATLAB classes of our own. MATLAB provides an interface to the Java programming language that enables us to create objects from Java classes and call Java methods on these objects. A Java class is a MATLAB data type. A function handle holds information to be used in referencing a function. When you create a function handle, MATLAB captures all the information about the function that it needs to locate and execute, or evaluate, it later on. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 17 The following table describes the data types in more detail. Data Type Example Description single 3*10^38 Single-precision numeric array. Single precision requires less storage than double precision, but has less precision and a smaller range. This data type cannot be used in mathematical operations. double 3*10^300 5+6i Double-precision numeric array. This is the most common MATLAB variable type. sparse speye(5) Sparse double-precision matrix (2-D only). The sparse matrix stores matrices with only a few nonzero elements in a fraction of the space required for an equivalent full matrix. Sparse matrices invoke special methods especially tailored to solve sparse problems. int8, uint8, int16,uint16, int32,uint32 uint8(magic(3)) Signed and unsigned integer arrays that are 8, 16, and 32 bits in length. Enables you to manipulate integer quantities in a memory efficient manner. These data types cannot be used in mathematical operations. char 'Hello' Character array (each character is 16 bits long). This array is also referred to as a string. cell {17 'hello' eye(2)} Cell array. Elements of cell arrays contain other arrays. Cell arrays collect related data and information of a dissimilar size together. structure a.day = 12; a.color = 'Red'; a.mat = magic(3); Structure array. Structure arrays have field names. The fields contain other arrays. Like cell arrays, structures collect related data and information together. user class inline('sin(x)') MATLAB class. This user-defined class is created using MATLAB functions. java class java.awt.Frame Java class. You can use classes already defined in the Java API or by a third party, or create your own classes in the Java language. functionhandle @humps Handle to a MATLAB function. A function handle can be passed in an argument list and evaluated using feval. Examples: >> format long >> pi ans = 3.14159265358979 >> format short >> pi Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 18 ans = 3.1416 Complex numbers: >> (1+3i)/(1-3i) ans = -0.8000 + 0.6000i Arithmetic Operators + Addition or unary plus. A+B; adds A and B. - Subtraction or unary minus. A-B; subtracts B from A. * Matrix multiplication. C = A*B is the linear algebraic product of the matrices A and B. .* Array multiplication: A.*B is the element-by-element product of the arrays A and B. A and B must have the same size, unless one of them is a scalar. / Slash or matrix right division. B/A is roughly the same as B*inv(A). More precisely, B/A =(A'\B')'. ./ Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the same size, unless one of them is a scalar. \ Backslash or matrix left division. If A is a square matrix, A\B is roughly the same as inv(A)*B, except it is computed in a different way. .\ Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A and B must have the same size, unless one of them is a scalar. ^ Matrix power. X^p is X to the power p, if p is a scalar. .^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A and B must have the same size, unless one of them is a scalar. ' Matrix transpose. A' is the linear algebraic transpose of A. .' Array transpose. A.' is the array transpose of A. For complex matrices, this does not involve conjugation. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 19 Syntax A+B A-B A*B A.*B A/B A./B A\B A.\B A^B A.^B A' A.' Relational Operators Operator Description < Less than <= Less than or equal to > Greater than >= Greater than or equal to == Equal to ~= Not Equal to Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 20 MATLAB provides the following logical operators. Operator Description & AND | OR ~ NOT Logical operations Syntax A & B A | B ~A Description : The symbols &, |, and ~ are the logical operators and, or, and not respectively. They work element-wise on arrays, with 0 representing logical false (F), and anything nonzero representing logical true (T). The & operator does a logical and, The | operator does a logical or, and ~A complements the elements of A. The function xor(A,B) implements the exclusive or operation. Operator Precedence It can build expressions that use any combination of arithmetic, relational, and logical operators. Precedence levels determine the order in which MATLAB evaluates an expression. The precedence rules for MATLAB operators from highest precedence level to lowest precedence level: 1. Parentheses () 2. Transpose(.'), power(.^), complex conjugate transpose('), matrix power(^) 3. Unary plus (+), unary minus (-), logical negation (~) 4. Multiplication (.*), right division (./), left division(.\), matrix multiplication (*), matrix right division (/), matrix left division (\) 5. Addition (+), subtraction (-) 6. Colon operator (:) 7. Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=) 8. Logical AND (&) 9. Logical OR (|) Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 21 Control Statements: • MATLAB has several flow control constructs: 1. The if – end Structure 2. The If- else- end Structure 3. The If- elseif-else- end Structure 4. The switch-case statements 5. for loops 6. while loops 7. continue statements 8. break statements if statements • The if statement evaluates a logical expression and executes a group of statements when the expression is true. if rem(n,2) ~= 0 M = odd_magic(n) elseif rem(n,4) ~= 0 M = single_even_magic(n) else M = double_even_magic(n) end The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, which matches the if, terminates the last group of statements. The groups of statements are delineated by the four keywords - no braces or brackets are involved. switch and case The switch statement executes groups of statements based on the value of a variable or expression. The keywords case and otherwise separates the groups. Only the first matching case is executed. There must always be an end to match the switch. The logic of the magic squares algorithm can also be described by The logic of the magic squares algorithm can also be described by switch (rem(n,4)==0) + (rem(n,2)==0) case 0 Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 22 M = odd_magic(n) case 1 M = single_even_magic(n) case 2 M = double_even_magic(n) otherwise error('This is impossible') end Example : Also let us implement simple switch function as follows: n=input('enter a number') switch (rem(n,4) + rem(n,2)) case 0 M = 5 case 1 M = 10 case 2 M = 27 otherwise error('This is impossible') end • Note Unlike the C language switch statement, MATLAB's switch does not fall through. If the first case statement is true, the other case statements do not execute. So, break statements are not required. for The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements. for n = 3:32 r(n) = rank(magic(n)); end r The semicolon terminating the inner statement suppresses repeated printing, and the r after the loop displays the final result. It is a good idea to indent the loops for readability, especially when they are nested. for i = 1:m for j = 1:n H(i,j) = 1/(i+j); end end Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 23 while • The while loop repeats a group of statements for an indefinite number of times under control of a logical condition. A matching end delineates the statements. Here is a complete program, illustrating while, if, else, and end, that uses interval bisection to find a zero of a polynomial. a = 0; fa = -Inf; b = 3; fb = Inf; while b-a > eps*b x = (a+b)/2; fx = x^3-2*x-5; if sign(fx) == sign(fa) a = x; fa = fx; else b = x; fb = fx; end end x The result is a root of the polynomial x 3 - 2x - 5, namely x = 2.09455148154233 continue • The continue statement passes control to the next iteration of the for or while loop in which it appears, skipping any remaining statements in the body of the loop. In nested loops, continue passes control to the next iteration of the for or while loop enclosing it. break The break statement lets us exit early from a for or while loop. In nested loops, break exits from the innermost loop only. a = 0; fa = -Inf; b = 3; fb = Inf; while b-a > eps*b x = (a+b)/2; fx = x^3-2*x-5; if fx == 0 break elseif sign(fx) == sign(fa) a = x; fa = fx; else b = x; fb = fx; end end x Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 24 return return terminates the current sequence of commands and returns control to the invoking function or to the keyboard. return is also used to terminate keyboard mode. Creating and Working with Arrays of Numbers An array is a list of numbers or expressions arranged in horizontal rows and vertical columns. When an array has only one row or column, it is called a vector. >> x = [1 2 3] x = 1 2 3 >> y = [2; 1; 5] y = 2 1 5 >> z = [2 1 0] z = 2 1 0 >> a = x+z a = 3 3 3 >> b = x+y ??? Error using ==> + Matrix dimensions must agree. >> >> a =x.*z a = 2 2 0 >> > x = linspace(0, 10 ,5) x = 0 2.5000 5.0000 7.5000 10.0000 >> y = sin(x) y = 0 0.5985 -0.9589 0.9380 -0.5440 >> z = sqrt(x).*y z = 0 0.9463 -2.1442 2.5688 -1.7203 >> Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 25 Creating and Printing Simple plots: plot - creates a 2-D line plot. axis - changes the aspect ratio of x and y axes. >> theta = linspace(0,2*pi,100); >> x=cos(theta); >> y=sin(theta); >> plot(x,y) >> axis('equal'); >> xlabel('x') >> ylabel('y') >> title('Circle of unit radius') >> Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 26 Matrices and Vectors • A matrix is entered row-wise with consecutive elements of a row separated by a space or comma, and the rows separated by semicolon or carriage returns. >> A=[1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 • Once a matrix exists, its elements are accessed by specifying their row and column indices. Thus A(i,j) in MATLAB refers to the element a i,j of matrix A, i.e, the element in the i th row and j th column. >> A(2,3) ans = 6 >> A(3,3)=8 A = 1 2 3 4 5 6 7 8 8 >> B=A(2:3,1:3) B = 4 5 6 7 8 8 • Matrix dimensions are determined automatically by MATLAB, i.e., no explicit dimension declarations are required. The dimensions of an existing matrix A may be obtained with the command size(A) or more explicitly with [m,n] = size(A), which assigns the number of rows and columns of A to the variables m and n, respectively. >> [m,n]=size(A) m = 3 n = 3 >> Reshaping matrices Matrices can be reshaped into a vector or any other appropriately sized matrix: • As a vector : All the elements of a matrix A can be strung into a single column vector b by the command b = A(:) >> A A = 1 2 3 4 5 6 7 8 8 Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 27 >> b =A(:) b = 1 4 7 2 5 8 3 6 8 >> • As a differently sized matrix: If matrix is an m×n, it can be reshaped into a p×q, as long as m×n= p×q, with the command reshape(A,p,q). >> A = [1 2 3 4;5 6 7 8;9 10 11 12] A = 1 2 3 4 5 6 7 8 9 10 11 12 >> reshape(A,2,6) ans = 1 9 6 3 11 8 5 2 10 7 4 12 Transpose • The transpose of a matrix A is obtained by typing A’. >> A = [1 2;3 4] A = 1 2 3 4 >> A' ans = 1 3 2 4 >> B=[1+2i 2+2i; 3i 2-2i] B = 1.0000 + 2.0000i 2.0000 + 2.0000i 0 + 3.0000i 2.0000 - 2.0000i >> B' ans = 1.0000 - 2.0000i 0 - 3.0000i 2.0000 - 2.0000i 2.0000 + 2.0000i >> Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 28 Initialization Inialization of a matrix is not necessary in MATLAB. However, it is advisable in the following two cases: • Large matrices: Initialization of the matrix to a zero matrix of the required dimension. An m×n matrix can be initialized by the command A =zeros(m,n). • Dynamic matrices: If the rows or columns of a matrix are computed in a loop and appended to the matrix in each execution of the loop. A null matrix A is created by the command A = []. Appending a row or column A row can be easily appended to an existing matrix provided the roe has the same length as the length of the rows of the matrix. The same thing goes for columns. • The command A = [A u] appends the column vector u to the columns of A, while A = [A;v] appends the row vector v to the rows of A. A row or column of any size may be appended to a null matrix. >> A=[1 2 3;4 5 6;7 8 9] A = 1 2 3 4 5 6 7 8 9 >> u=[9;8;8] u = 9 8 8 >> A=[A u] A = 1 2 3 9 4 5 6 8 7 8 9 8 >> v=[9 9 9 9] v = 9 9 9 9 >> A=[A;v] A = 1 2 3 9 4 5 6 8 7 8 9 8 9 9 9 9 >> A=[A v] ??? Error using ==> horzcat All matrices on a row in the bracketed expression must have the same number of rows. >> Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 29 Deleting a row or column • Any row(s) or column(s) of a matrix can be deleted by setting the row or column to a null vector. Example: A(2,:) = [] deletes the 2 nd row of the matrix A, A(:,3:5) = [] deletes the 3 rd through 5 th columns of A, A([1 3], :) = [] deletes the 1 st and the 3 rd row of A, u(5:length(u)) = [] deletes all elements of vector u except 1 through 4. >> A A = 1 2 3 9 4 5 6 8 7 8 9 8 9 9 9 9 >> A(2,:)=[] A = 1 2 3 9 7 8 9 8 9 9 9 9 >> A(:,2:4)=[] A = 1 7 9 >> A([1 3],:)=[] A = 7 >> Utility matrices To aid matrix generation and manipulation, MATLAB provides many useful utility matrices. For example eye(m,n) returns an m by n matrix with 1’s on the main diagonal. zeros(m,n) returns an m by n matrix of zeros. ones(m,n) returns an m by n matrix of ones. rand(m,n) returns an m by n matrix of random numbers randn(m,n) returns an m by n matrix of normally distributed numbers. diag(v) generates a diagonal matrix with vector v on the diagonal. diag(A) extracts the diagonal of matrix A as a vector. diag(A,1) extracts the first vector off-diagonal vector of matrix A. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 30 Creating Vectors The general command to do this in MATLAB is v = intialValue : Increment : FinalValue If no increment is specified, MATLAB uses the default increment of 1. linspace(a, b, n) generates a linearly spaced vector of length n from a to b. >> u = linspace(0,20,5) u = 0 5 10 15 20 logspace(a, b, n) generates a linearly spaced vector of length n from 10 a to 10 b . >> v = logspace(0,3,4) v = 1 10 100 1000 >> The left division: • In addition to the normal or right division (/), there is a left division (\) in MATLAB. This division is used to solve a matrix equation. In particular, the command x=A\b solves the matrix equation AX=b and almost same as inv(A)*b, but faster and more numerically stable than computing inv(A)*b. Array operation: • Array operations done on element –by-element basis. Element –by-element multiplication, division, and exponentiation between two matrices or vector of the same size are done by preceding the corresponding arithmetic operators by a period (.). Some of the matrix functions are : expm(A) finds the exponential of matrix A, e A . logm(A) finds log(A) such that A = e log(A) sqrtm(A) finds square root of A. >> A = [ 1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >> sqrt_A = sqrt(A) sqrt is an array operation. It gives the square root of each element of A . sqrt_A = 1.0000 1.4142 1.7321 2.0000 2.2361 2.4495 2.6458 2.8284 3.0000 >> asqrt = sqrtm(A) sqrtm, on the other hand, is a true matrix function i.e., it computes A . Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 31 Thus [asqrt]*[asqrt]=A asqrt = 0.4498 + 0.7623i 0.5526 + 0.2068i 0.6555 - 0.3487i 1.0185 + 0.0842i 1.2515 + 0.0228i 1.4844 - 0.0385i 1.5873 - 0.5940i 1.9503 - 0.1611i 2.3134 + 0.2717i >> eig(a) ans = 16.1168 -1.1168 -0.0000 >> Note: SQRTM Matrix square root. X = SQRTM(A) is the principal square root of the matrix A, i.e. X*X = A. X is the unique square root for which every eigenvalue has nonnegative real part. If A has any eigenvalues with negative real parts then a complex result is produced. If A is singular then A may not have a square root. A warning is printed if exact singularity is detected. Example: >> a =[1 0;0 2] a = 1 0 0 2 >> sqrtm(a) ans = 1.0000 0 0 1.4142 >> >> exp_a = exp(A) exp_a = 1.0e+003 * 0.0027 0.0074 0.0201 0.0546 0.1484 0.4034 1.0966 2.9810 8.1031 Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 32 >> exp_aij=expm(A) exp_aij = 1.0e+006 * 1.1189 1.3748 1.6307 2.5339 3.1134 3.6929 3.9489 4.8520 5.7552 eig(A) : To find both the eigenvalues and eigenvectors of A. The output can listed explicitly by using the following: [eigvec, eigval] = eig(A) Function files A function file begins with a function definition line, which has a well defined list of inputs and outputs. Without this line, the file becomes a script file. The syntax of the function definition line is as follows: function [output variables] = function_name(input variables) where the function_name must be the same as the filename in which the function written. Example: function [x,y] = circlefn(r); % CIRCLE - A function to draw a circle of radius r. % File written by Dr. N. Yadaiah %Call synatx: [x,y] = circlefn(r); or just : circlefn(r); %Input: r=specified radius %Output: [x,y] = the x - and y - coordinates of data points theta = linspace(0,2*pi,100); % create vector theta x = r*cos(theta); % generate x - coordinates y = r*sin(theta); % generate x - coordinates plot(x,y); %plot the circle axis('equal'); %set equal scale on axes title(['Circle of radius r = ',num2str(r)]) %put a title with the value of r Local and Global Variables • Each MATLAB function, defined by an M-file, has its own local variables, which are separate from those of other functions, and from those of the base workspace. • However, if several functions, and possibly the base workspace, all declare a particular name as global, then they all share a single copy of that variable. Any assignment to that variable, in any function, is available to all the other functions declaring it global. • MATLAB variable names consist of a letter followed by any number of letters, digits, and underscores. MATLAB distinguishes between uppercase and lowercase characters, so A and a are not the same variable. MATLAB uses only the first 31 characters of variable names. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 33 Interactive input The commands – input, keyword, menu, and pause can be used inside a script or a function file for interactive user input. Input : Request user input Syntax user_entry = input('prompt') user_entry = input('prompt','s') Description The response to the input prompt can be any MATLAB expression, which is evaluated using the variables in the current workspace. user_entry = input('prompt') displays prompt as a prompt on the screen, waits for input from the keyboard, and returns the value entered in user_entry. user_entry = input('prompt','s') returns the entered string as a text variable rather than as a variable name or numerical value. File I/O File Opening, Closing, and Positioning fopen, fclose, fseek, ftell, frewind, ferror. File Reading and Writing fread, fwrite, fprintf, fscanf, fgetl, fgets. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 34 fopen : Open a file or obtain information about open files Syntax fid = fopen(filename) fid = fopen(filename, permission) [fid, message] = fopen(filename, permission, machineformat) fids = fopen('all') [filename, permission, machineormat] = fopen(fid) Description fid = fopen(filename) :opens the file filename for read access. (On PCs, fopen opens files for binary read access.) fid is a scalar MATLAB integer, called a file identifier. The fid will be used as the first argument to other file input/output routines. If fopen cannot open the file, it returns -1. Two file identifiers are automatically available and need not be opened. They are fid=1 (standard output) and fid=2 (standard error). fid = fopen(filename, permission) opens the file filename in the mode specified by permission. permission can be: 'r' : Open file for reading (default). 'w' : Open file, or create new file, for writing; discard existing contents, if any. 'a' : Open file, or create new file, for writing; append data to the end of the file. 'r+' : Open file for reading and writing. 'w+' : Open file, or create a new file, for reading and writing; discard existing contents, if any. 'a+' : Open file, or create new file, for reading and writing; append data to the end of the file. 'A' : Append without automatic flushing; used with tape drives 'W' : Write without automatic flushing; used with tape drives • filename can be a MATLABPATH relative partial pathname if the file is opened for reading only. A relative path is always searched for first with respect to the current directory. If it is not found and reading only is specified or implied then fopen does an additional search of the MATLABPATH [fid, message] = fopen(filename, permission) opens a file as above. If it cannot open the file, fid equals -1 and message contains a system-dependent error message. If fopen successfully opens a file, the value of message is empty. [fid, message] = fopen(filename,permission,machineformat) opens the specified file with the specified permission and treats data read using fread or data written using fwrite as having a format given by machineformat. machineformat is one of the following strings: 'cray' or 'c' : Cray floating point with big-endian byte ordering 'ieee-be' or 'b' : IEEE floating point with big-endian byte ordering Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 35 'ieee-le' or 'l' : IEEE floating point with little-endian byte ordering 'ieee-be.l64' or 's' : IEEE floating point with big-endian byte ordering and 64-bit long data type 'ieee-le.l64' or 'a' : IEEE floating point with little-endian byte ordering and 64-bit long data type 'native' or 'n' : Numeric format of the machine on which MATLAB is running (the default). 'vaxd' or 'd' : VAX D floating point and VAX ordering 'vaxg' or 'g' : VAX G floating point and VAX ordering fids = fopen('all') returns a row vector containing the file identifiers of all open files, not including 1 and 2 (standard output and standard error). The number of elements in the vector is equal to the number of open files. [filename, permission, machineformat] = fopen(fid) returns the filename, permission string, and machineformat string associated with the specified file. An invalid fid returns empty strings for all output arguments. The 'W' and 'A' permissions are designed for use with tape drives and do not automatically perform a flush of the current output buffer after output operations. For example, open a 1/4" cartridge tape on a SPARCstation for writing with no auto-flush: fid = fopen('/dev/rst0','W') Example The example uses fopen to open a file and then passes the fid, returned by fopen, to other file I/O functions to read data from the file and then close the file. fid=fopen('fgetl.m'); while 1 tline = fgetl(fid); if ~ischar(tline), break, end disp(tline) end fclose(fid); Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 36 fscanf : Read formatted data from file Syntax A = fscanf(fid,format) [A,count] = fscanf(fid,format,size) Description A = fscanf(fid, format) reads all the data from the file specified by fid, converts it according to the specified format string, and returns it in matrix A. Argument fid is an integer file identifier obtained from fopen. format is a string specifying the format of the data to be read. [A,count] = fscanf(fid, format,size) reads the amount of data specified by size, converts it according to the specified format string, and returns it along with a count of elements successfully read. size is an argument that determines how much data is read. Valid options are: n : Read n elements into a column vector. inf : Read to the end of the file, resulting in a column vector containing the same number of elements as are in the file. [m,n]: Read enough elements to fill an m-by-n matrix, filling the matrix in column order. n can be Inf, but not m. fscanf differs from its C language namesakes scanf() and fscanf() in an important respect -- it is vectorized in order to return a matrix argument. The format string is cycled through the file until an end-of-file is reached or the amount of data specified by size is read in. Valid conversion characters are: %c : Sequence of characters; number specified by field width %d : decimal numbers %e, %f, %g :Floating-point numbers %i : Signed integer %o : Signed octal integer %s : A series of non-white-space characters %u : Signed decimal integer %x : Signed hexadecimal integer [...] : Sequence of characters (scanlist) If %s is used, an element read may use several MATLAB matrix elements, each holding one character. Use %c to read space characters or %s to skip all white space. Mixing character and numeric conversion specifications cause the resulting matrix to be numeric and any characters read to appear as their ASCII values, one character per MATLAB matrix element. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 37 For more information about format strings, refer to the scanf() and fscanf() routines in a C language reference manual. Examples The example in fprintf generates an ASCII text file called exp.txt that looks like: 0.00 1.00000000 0.10 1.10517092 ... 1.00 2.71828183 Read this ASCII file back into a two-column MATLAB matrix: fid = fopen('exp.txt'); a = fscanf(fid,'%g %g',[2 inf]) % It has two rows now. a = a'; fclose(fid) fread : Read binary data from file Syntax [A,count] = fread(fid,size,precision) [A,count] = fread(fid,size,precision,skip) Description [A,count] = fread(fid,size,precision) reads binary data from the specified file and writes it into matrix A. Optional output argument count returns the number of elements successfully read. fid is an integer file identifier obtained from fopen. n :Reads n elements into a column vector. Inf : Reads to the end of the file, resulting in a column vector containing the same number of elements as are in the file. [m,n] : Reads enough elements to fill an m-by-n matrix, filling in elements in column order, padding with zeros if the file is too small to fill the matrix. n can be specified as inf, but m cannot. precision is a string that specifies the format of the data to be read. It commonly contains a datatype specifier such as int or float, followed by an integer giving the size in bits. Any of the strings in the following table, either the MATLAB version or their C or Fortran equivalent, may be used. If precision is not specified, the default is 'uchar'. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 38 The following platform dependent formats are also supported but they are not guaranteed to be the same size on all platforms. The following formats map to an input stream of bits rather than bytes. By default, numeric values are returned in class 'double' arrays. To return numeric values stored in classes other thatn double, create your precision argument by first specifying your source format, then following it with the characters "=>", and finally specifying your destination format. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 39 fread (serial) : Read binary data from the device Syntax A = fread(obj,size) A = fread(obj,size,'precision') [A,count] = fread(...) [A,count,msg] = fread(...) Arguments obj A serial port object. Size The number of values to read. 'precision' The number of bits read for each value, and the interpretation of the bits as character, integer, or floating-point values. A Binary data returned from the device. count The number of values read. msg A message indicating if the read operation was unsuccessful. Description A = fread(obj, size) reads binary data from the device connected to obj, and returns the data to A. strread Read formatted data from a string Syntax A = strread('str') A = strread('str','',N) A = strread('str','',param,value,...) A = strread('str','',N,param,value,...) [A,B,C,...] = strread('str','format') [A,B,C,...] = strread('str','format',N) [A,B,C,...] = strread('str','format',param,value,...) [A,B,C,...] = strread('str','format',N,param,value,...) Description The first four syntaxes are used on strings containing only numeric data. If the input string, str, contains any text data, an error is generated. A = strread('str') reads numeric data from the string, str, into the single variable A. A = strread('str','',N) reads N lines of numeric data, where N is an integer greater than zero. If N is -1, strread reads the entire string. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 40 A = strread('str','',param,value,...) customizes strread using param/value pairs, as listed in the table below. A = strread('str','',N,param,value,...) reads N lines and customizes the strread using param/value pairs. The next four syntaxes can be used on numeric or nonnumeric data. In this case, strread reads data from the string, str, into the variables A, B, C, and so on, using the specified format. The functions associated with reading data are given below. Function Name Description fgetl Read one line of text from the device and discard the terminator fgets Read one line of text from the device and include the terminator fread Read binary data from the device fscanf Read data from the device, and format as text feadasync Read data asynchronously from the device ftopasync Stop asynchronous read and write operations The properties associated with reading data are given below. BytesAvailable Indicate the number of bytes available in the input buffer InputBufferSize Specify the size of the input buffer in bytes ReadAsyncMode Specify whether an asynchronous read operation is continuous or manual. Timeout Specify the waiting time to complete a read or write operation TransferStatus Indicate if an asynchronous read or write operation is in Progress ValuesReceived Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 41 print, printopt : Create hardcopy output Syntax print print -device -options filename [pcmd,dev] = printopt Description print and printopt produce hardcopy output. All arguments to the print command are optional. print sends the contents of the current figure, including bitmap representations of any user interface controls, to the printer using the device and system printing command defined by printopt. print(...) is the function form of print. It enables you to pass variables for any input arguments. This form is useful passing filenames and handles. See Batch Processing for an example. [pcmd,dev] = printopt returns strings containing the current system-dependent printing command and output device. printopt is an M-file used by print to produce the hardcopy output. You can edit the M-file printopt.m to set your default printer type and destination. fprintf : Write formatted data to file Syntax count = fprintf(fid, format, A,...) Description count = fprintf(fid,format,A,...) formats the data in the real part of matrix A (and in any additional matrix arguments) under control of the specified format string, and writes it to the file associated with file identifier fid. fprintf returns a count of the number of bytes written. Argument fid is an integer file identifier obtained from fopen. (It may also be 1 for standard output (the screen) or 2 for standard error. Omitting fid causes output to appear on the screen. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 42 Applications 1. Linear Algebra (i) Solving a linear system ( Set of simultaneous equations) Step 1: Rearrange equations Step 2: Write the equations in matrix form Step 3: Solve the matrix equation in MATLAB Example: Solve the following set of equations: 5x =3y-2z+10 8y+4z=3x+20 2x+4y-9z=9 Step 1: 5x-3y+2z = 10 -3x+8y+4z = 20 2x+4y-9z = 9 Step 2: ] ] ] ] ] · ] ] ] ] ] − − − · ] ] ] ] ] · 9 20 10 b ; 9 4 2 4 8 3 2 3 5 A ; z y x X Step 3: >> A=[5 -3 2;-3 8 4;2 4 -9] A = 5 -3 2 -3 8 4 2 4 -9 >> b=[10;20;9] b = 10 20 9 >> X=A\b X = 3.4442 3.1982 1.1868 >> Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 43 2. Gaussian Elimination The above equations can be solved by Gaussian elimination method. This technique requires forming a rectangular matrix that contains both the coefficient matrix A and the known vector b in an augmented matrix. Gauss-Jordan reduction procedure is then used to transform the augmented matrix to the so called row reduced echelon form. MATLAB has a built-in function, rref that does precisely this reduction, i.e., transforms the matrix to its row reduction echelon form. The last column of the reduced augmented matrix is the solution of the given equations. Example: Let us solve the above example by using this method. >> C=[A b] C = 5 -3 2 10 -3 8 4 20 2 4 -9 9 >> Cr = rref(C) Cr = 1.0000 0 0 3.4442 0 1.0000 0 3.1982 0 0 1.0000 1.1868 >> The last column of the matrix Cr is the solution. 3. Finding eigenvalues & eigenvectors The eigenvalue problem in scientific computation show up as Av = λv (1) where λ is a scalar. The problem is to find λ and v for a given A so that equation (1) is satisfied. Step 1: Enter the matrix A and type [V, D] = eig(A) Step 2: Extract what is required. In the output list, V is an n×n matrix whose columns are eigen vectors and D is an n×n diagonal matrix which has the eigenvalues of A on its diagonal. The function eig can also be used with one output argument, ex: lamdas=eig(A), in which case the function gives only the eigenvalues in the vector lamdas. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 44 Example: Let us find the eigenvalues and eigenvectors of the above matrix A. >> [V,D]=eig(A) V = -0.1709 0.8729 0.4570 -0.2365 0.4139 -0.8791 0.9565 0.2583 -0.1357 D = -10.3463 0 0 0 4.1693 0 0 0 10.1770 >> lamdas=eig(A) lamdas = -10.3463 4.1693 10.1770 >> 4. Matrix factorizations (i) LU factorization: The name of built-in function is lu. [L, U] = lu(A) MATLAB returns a lower triangular matrix L amd an upper triangular matrix U such that L*U = A >> A=[5 -3 2;-3 8 4; 2 4 -9] A = 5 -3 2 -3 8 4 2 4 -9 >> [L, U] = lu(A) L = 1.0000 0 0 -0.6000 1.0000 0 0.4000 0.8387 1.0000 U = 5.0000 -3.0000 2.0000 0 6.2000 5.2000 0 0 -14.1613 >> a = L*U a = 5.0000 -3.0000 2.0000 -3.0000 8.0000 4.0000 2.0000 4.0000 -9.0000 (ii) QR factorization: The name of the built-in function is qr. [Q,R]=qr(A) MATLAB returns an orthogonal matrix Q and an upper triangular matrix R such that Q*R = A. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 45 A = 5 -3 2 -3 8 4 2 4 -9 >> [Q,R]=qr(A) Q = -0.8111 -0.1352 -0.5691 0.4867 -0.6957 -0.5284 -0.3244 -0.7055 0.6300 R = -6.1644 5.0289 3.2444 0 -7.9819 3.2969 0 0 -8.9221 >> b=Q*R b = 5.0000 -3.0000 2.0000 -3.0000 8.0000 4.0000 2.0000 4.0000 -9.0000 >> (iii) Singular Value Decomposition(svd): The name of the built-in function is svd. The following syntax is used to obtained svd for A. [U, D, V] = svd(A) MATLAB returns two orthogonal matrices U and V, and a diagonal matrix D, with the singular values of A as the diagonal entries, such that U*D*V = A. >> A A = 5 -3 2 -3 8 4 2 4 -9 >> [U,D, V] = svd(A) U = -0.1709 0.4570 0.8729 -0.2365 -0.8791 0.4139 0.9565 -0.1357 0.2583 D = 10.3463 0 0 0 10.1770 0 0 0 4.1693 V = 0.1709 0.4570 0.8729 0.2365 -0.8791 0.4139 -0.9565 -0.1357 0.2583 >> c = U*D*V c = -2.6833 -5.3901 1.3217 -4.1844 6.5120 -5.3930 0.3345 5.5902 8.3449 Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 46 5. Nonlinear Algebraic Equations The MATLAB function fzero solves nonlinear equations involving one variable. The following steps are used to solve the equation: Step 1: Write the equation in the standard form: f(x) = 0 This step involves trivial rearrangement of the given equation. Step 2: Write a function that computes f(x) : The function should return the value of f(x) at any given x. Step 3: Use the built-in function fzero to find the solution: fzero requires an initial guess and returns the value of x closest to the guess at which f(x) is zero. x_sol = fzero(‘function’, x 0 , tol, trace) where: x_sol → the solution, function → f(x), x 0 →initial guess tol, trace → optional arguments function f= transf(x); %TRANSF: computes f(x) = sin(x)-exp(x)+5 %call syntax: f=transf(x) f = sin(x) - exp(x) + 5; >> x = fzero('transf',1) x = 1.7878 >> 6. Numerical Integration (Quadrature) Numerical evaluation of the integral ∫ dx x f ) ( is called quadrature. Most often, the integrand analytically. In such cases, we integrate numerically. However, we can integrate only evaluate definite integrals, i.e., ∫ b a dx x f ) ( , numerically. MATLAB provides the following built-in functions for numerical integration: quad: It integrates a specified function over specified limits, based on adaptive Simpson’s rule. quadl: It integrates a specified function over specified limits, based on adaptive Lobatto quadrature. This one is more accurate than quad but it also uses more function evaluations. The general call syntax for both quad and quadl is as follows: Integral = quad(‘function’, a,b, tol, trace, p1, p2, . . ) Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 47 where, function → function to be integrated ( integrand f(x)) ; a,b → limits of integration, tol → absolute tolerance ( the default value is 10 -6 ). A nonzero value of the other optional argument, trace, shows some intermediate calculations at each step. To use quadl, just replace quad with quadl in the above syntax. The following steps are involved in numerical integration using these built-in functions: Step 1: Write a function that returns the value of integrand f(x) given the value of x. It should be able accept the input x as a vector and corresponding produce the value of the integrand as a vector. Step 2: Decide which function to use – quad or quadl (quad is faster but less accurate than quadl). Example: Compute the following integral ∫ − 2 / 3 2 / 1 2 dx e x Solution: Step 1: function y = expf(x); % expf function to evaluate exp(-x^2) y = exp(-x.^2); % the .^ operator is used for vector x Step 2: >> y=quad('expf',1/2,3/2) y = 0.39490739269182 >> y=quadl('expf',1/2,3/2) y = 0.39490738751836 >> 7. Double Integration To evaluate integrals of the form ∫ ∫ max min max min dy ) , ( y y x x dx y x f MATLAB provides a function dblquad. The calling syntax for dblquad is: I = dblquad(‘fxy_fun’, xmin, xmax, ymin, ymax, tol, method) where tol, method are optional arguments. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 48 Example: Compute the following integral: I = ∫ ∫ − − 1 2 0 2 dy ) 6 1 ( dx y x >> f=inline('1-6*x.^2*y'); >> I = dblquad(f,0,2,-1,1) I = 4.00000000000000 >> 8. Ordinary Differential Equations In MATLAB the functions, ode23 and ode45 are implementations of 2 nd /3 rd – order and 4 th /5 th – order Runge-Kutta methods, respectively. Solving most ordinary differential equations (ODEs) using these functions involves the following steps: Step 1: Write the differential equation(s) as a set of first-order ODEs For ODEs of order ≥2, this step involves introducing new variables and recasting the original equation(s) in terms of 1 st -order ODEs in the new variables and their vector form as: ) , ( t x f x · ! , where x = [x 1 x 2 . . . x n ] T . That is ¹ ¹ ¹ ¹ ¹ ' ¹ ¹ ¹ ¹ ¹ ¹ ' ¹ · ] ] ] ] ] ] ) , x . . . x , ( . ) , x . . . x , ( ) , x . . . x , ( . n 2 1 n 2 1 2 n 2 1 1 2 1 t x f t x f t x f x x x n n ! ! ! Step 2: Write a function to compute the state derivative. Step 3: Use the built-in ODE solvers ode23 or ode45 to solve the equations The syntax of use of ode23 is shown below. To use ode45 just replace ‘ode23’ with ‘ode45’. [time, solution] =ode23(‘function’,tspan, x 0 ) where , time → time vector; solution → solution matrix; function → xdot = function(t,x); tspan → time span [t 0 t final ]; x 0 → initial condition. Step 4: Extract the desired variables from the output and interpret the variables. Example: Solve the equation of motion of a nonlinear pendulum θ ω θ θ ω θ sin 0 sin 2 2 − · ⇒ · + ! ! ! ! with the initial conditions θ(0) = 1 , 0 ) 0 ( · θ ! Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 49 Solution: Step 1: Let us introduce two new variables and are z 1 = θ and z 2 = θ ! . Then 2 1 z z · ·θ ! ! and ). sin( 1 2 2 z z ω θ − · · ! ! ! ¹ ' ¹ ¹ ' ¹ − · ¹ ¹ ¹ ' ¹ ¹ ¹ ¹ ' ¹ • • ) sin( 1 2 1 2 1 z z z z ω ) (z f z · ! Step 2 : Write a function to compute the new state derivative: function zdot = pend(t,z) % Call syntax : zdot = pend(t,z) % Inputs are : t = time, z=[z(1), z(2)] = [theta; thetdot] % Output is : zdot = [z(2); - w^2sin(z(1)] wsq = 1.56 % specify a value of w^2 zdot = [z(2); -wsq*sin(z(1))]; Step 3: Use ode23 or ode45 for solution: tspan = [0 20]; z0 =[1;0] % assign values to tspan, z0 [t,z] = ode23('pend', tspan, z0); % run ode23 x = z(:,1); y = z(:,2); % x = 1 st column of z, y = 2 nd column plot(t,x,t,y) %plot t vs x and t vs y xlabel (‘t’), ylabel(‘x and y’) Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 50 figure(2) % open a new figure window plot(x,y) % plot phase portrait xlabel(‘Displacement’), ylabel(‘Velocity’) title(‘Phase Plane of a nonlinear Pendulum’) % Put title Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 51 Control Systems? Overview of some control system ideas: • PLANT • SYSTEM • STATE PLANT I O Environment PLANT Controller + U(t) O Y desired - + Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 52 TYPES OF PROBLEMS P→ Plant I→ Input O→ Output 1. Analysis Given : I, P Find : O 2. Modeling ( Identification ) Given : I, O Find: P (a) Structure of identification (b) Parameter identification 3 Control: Given : P, O Find: I The purpose of the controller: (i) To get the desired response of the system (ii) To stabilize the system Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 53 Performance Objectives and Design Constraints • Disturbance rejection properties • Insensitivity to plant parameter variations • Stability • Rise-time • Overshoot • Settling time • Steady – State error While these factors are used to characterize the technical conditions that indicate whether or not a control system is performing properly, there are other issues that must be considered that are often of equal or greater importance. These include the following: • Coast • Computational complexity • Manufacturability • Reliability • Maintainability • Adaptability • Understandability • Politics Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 54 Conventional control has provided numerous methods for constructing controllers for dynamic systems. Some of these are : • Proportional-integral-derivative (PID) control • Classical control: Lead-lag compensation, Bode and Nyquist methods, root-locus design and so on. • State-space methods: State feedback, observers, and so on. • Optimal control: Linear quadratic regulator, use of Pontryagin’s minimum principle or dynamic programming, and so on. • Robust control: H 2 or H methods, quantitative feedback theory, loop shaping, and so on. • Nonlinear methods : Feedback linearization, Lyapunov redesign, sliding mode control, backstepping and so on. • Adaptive control: mode reference adaptive control, self-tuning regulators, nonlinear adaptive control, and so on. • Stochastic control : Minimum variance control, linear quadratic gaussian (LQG) control, stochastic adaptive control, and so on. • Discrete event systems: Petri nets, supervisory control, infinitesimal perturbation analysis, and so on. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 55 The main objectives of a Control System are: • Obtain the analysis of the systems in time domain. • Frequency response analysis (Stability , Sensitivity , Bandwidth , Accuracy .) • Stability analysis • Design of control Features • The Control System Toolbox implements the most prevalent “classical” and “modern” linear control techniques for the design and analysis of automatic control systems. • The Control System Toolbox lets the user to - model , - simulate , and - analyze LTI systems (Both continuous & discrete time). A sequence of characteristic steps of MATLAB based control system design follows: 1. Make the system model. : One of the first tasks is the development of the mathematical model of the process to be controlled. Basically there are few ways to generate model: (1) From the first principles of physics. (2) Perform system identification via the use of real plant data to produce a model of the system. (3) Combined approach. For example set first order differential equations as: ( ) t X • = f(X(t), u(t)) (1a) y(t) = g(X(t) u(t)) (1b) where f(.) and g(.) are nonlinear functions. 2. Determine the required performance specifications Requirements that a system have a step response inside some constraint boundaries – specified by rise time, settling time, peak overshoot etc., can equivalently be represented as requirements that the system have a frequency response satisfying certain constraints – specified by gain margin, phase margin and bandwidth, etc. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 56 3. Make a linear model From the specifications, identify the equilibrium point of interest and contruct a small-signal dynamic model. Validate the model with experimental data where possible. Linearization of equations of the form (1) leads to a model of the form given below: ( ) t X • = A X(t) + b u(t) (2a) y(t) = cX(t) + d u(t) (2b) where x - state vector , u - input , y - output . For convenience, the MATLAB provides customized data structure (LTI object). This is called the SS object. This object encapsulates the model data and enables you to manipulate the LTI system as a single entity, rather than as collection of data vectors and matrices. sys = ss(A,b,c,d) (3) creates the state-space model. For the above model, step(sys) will generate a plot of unit-step response y(t) ( with zero initial conditions). The time vector is automatically selected when t is not explicitly included in the step command. If you wish to supply the time vector t at which the response will be computed, the following command is used. Step(sys,t) You can specify either a final time t = Tfinal or a vector of evenly spaced time samples of the form t = 0: dt : Tfinal When invoked with left-hand arguments such as [y, t]= step(sys) [y, t, X] = step(sys) y = step(sys,t) no plot is generated on the screen. Hence it is necessary to use a plot command to see the response curves. The vector y and matrix X contain the output and state response of the system respectively, evaluated at the computation points returned in the time vector t. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 57 Other time-response functions of interest to us are >> step(sys); % step response. >> impulse(sys); % impulse response. >> initial(sys,xo); % undriven resp to initial condition. >> lsim(sys,u,t,xo); % response to input u. For MIMO models, these produce an array of plots. 4. Make a design model Depending on the type of model use, the data for the model may consist of a simple numerator/denominator pair for transfer functions or four matrices for state-space models. MATLAB provides LTI objects TF and SS for transfer function and state-space models respectively. An LTI object of the type TF is created whenever invoke the construction function tf. sys=tf(num, den) num and den vectors specify n(s) and d(s) respectively, of the transfer function G(s) = n(s)/d(s). Given the TF model sys_tf, the syntax for conversion to SS model is sys_ss = ss(sys_tf) MATLAB provides many functions for simulation of transfer functions. Process transfer function models frequently have deadtime (input-output delay). TF object for transfer functions with deadtime can be created using the syntax sys = tf(num, den, ‘InputDelay’, value) 5. Descretize the design model There are two alternative design procedures: Design using emulation: The design is done in the continuous-time domain totally ignoring the fact that a sampler and digital computer will eventually be used. Having the continuous-time controller, we then convert the design to a digital control. Direct digital design: Design the controller directly in discrete – time domain. MATLAB software has functions that allow use of various approximations. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 58 State-space model of a discrete-time SISO system is of the form X(k+1) = FX(k) + hu(k) Y(k) = c X(k) + du(k) Construction of the SS object for this discrete-time model requires four matrices F, h, c, and d and the sampling interval T. sysd = ss(F,h,c,d, ‘T’) Construction of the TF object for this discrete-time model requires num and den polynomials in z, and the sampling interval T. sysd = tf(num, den ‘T’) • To create discrete - time systems, sample-time ‘T’ has to be appended. sys1 = tf ( num,den,’T’ ) sys2 = zpk ( z,p,k, ‘T’ ) sys3 = ss ( a,b,c,d, ‘T’ ) Continuous/Discrete Conversions: The Control System toolbox provides the user an additional features (tools) for conversion of different LTI models : c2d, d2c, d2d. >> sysd = c2d(sysc,Ts); % continuous to discrete conversion . >> sysc = d2c(sysd); % discrete to continuous conversion. >> sysd1 = d2d(sysd,Ts); % resample discrete system or add inputdelay(s). Frequency Response : >> bode(sys); % Bode plot. >> nyquist(sys); % Nyquist plot. >> nichols(sys); % Nichols plot. >> sigma(sys); % singular value plot. >> freqresp(sys,w); % complex frequency response. Root Locus Design (GUI) • The root locus method is used for describing the trajectories of the closed- loop poles of a feedback system as one parameter varies over a continuous range of values. • In addition to plotting the rootlocus, the Root Locus Design GUI can be used to design a compensator interactively to meet some system design specifications. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 59 Root Locus Design (rltool) The Root Locus Design GUI can be used to: • Analyze the root locus plot for a SISO LTI control system. • Specify feedback compensator parameters: poles, zeros, gain. • Examine how the compensator parameters change the root locus, as well as various closed-loop system responses (step response, Bode plot, Nyquist plot, or Nichols chart). >> [p,z] = pzmap(sys) - pole - zero mapping. >> rltool - opens Root Locus Design GUI. >> rlocus(sys) - Root Locus plot. >> rlocfind(sys) - interactive root locus gain selection. >> sgrid - generates s-plane grid for root locus. >> zgrid - generates z-plane grid for root locus. Designing the compensator to meet specifications Specifying the design region boundaries on the root-locus Placing compensator poles and zeros Editing the compensator pole and zero locations Activating the compensator pole and zero locations Saving the compensator and models to the workspace or the disk. •Creating a transfer function: >>sys=tf([1 2],[1 1 10]) s + 2 Transfer function: ---------------- s^2 + s + 10 Model conversion: The functions tf, zpk, ss can also perform model conversion. Example: » h=tf(1,[1 2 1]) Transfer function : 1 ------------------- (s^2 + 2s + 1) » zpk(h) - zpk representation of the TF ‘h’ is derived. Zero/pole/gain : 1 ------------ (s +1)^2 Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 60 LTI Objects Objects store the model data and enable user to manipulate LTI system as a single entity, rather than collection of data vectors or matrices. For ex : >> p = tf( [1 2],[1 1 10]) >> bode(p) Operations on LTI models: • Simple matrix operations on LTI systems like addition, multiplication, or concatenation are possible. tf(1,[1 0])+tf([1 1],[1 2]) Transfer function: s^2 + 2 s + 2 ------------------ s^2 + 2 s Example: Consider wn = 5 rad/sec and damping ratio is 0.4. Generate the standard second order system. >> wn=5; >> damping_ratio=0.4; >> [num0,den]=ord2(wn,damping_ratio); >> num = 5^2*num0; >> printsys(num,den,'s') Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 61 num/den = 25 -------------- s^2 + 4 s + 25 >> • If operands are of different types, the resulting model type is determined by precedence rules. i.e.; ss > zpk > tf • System inversion, transposition, sub indexing, sub assignment are also supported. >> isys=inv(sys) % System inversion. >> sys.’ % Transpose of a LTI model. >> subsys=sys(3,1) % Subindexing. >> sys=[sys,h] % Subassignment. *** Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 62 /**** Prog1.m to find the transient specification of dynamical systems *****/ choice=input('enter "1" for I/O model and "2" for state space model\n') if(choice==1) num=input(' the numerator of the transfer function =') den=input('the denominator of the transfer function=') step(num,den) elseif(choice==2) a=input('system matrix a=') b=input('input matrix b=') c=input('output matrix c=') d=input('transportation matrix d=') step(a,b,c,d) [num,den]=ss2tf(a,b,c,d); end t=0:0.005:5; [y,x,t]=step(num,den,t); r=1;while y(r)<0.9;r=r+1;end; p=1;while y(p)<0.1;p=p+1;end; rise_time=((r-1)*0.005-(p-1)*0.005) [ymax,tp]=max(y); peak_time=(tp-1)*0.005 max_overshoot=ymax-1 s=1001;while y(s)>0.98 & y(s)<1.02;s=s-1;end; settling_time=(s-1)*0.005 >> prog1 enter "1" for I/O model and "2" for state space model 1 choice = 1 the numerator of the transfer function =1 num = 1 the denominator of the transfer function=[1 1 1] den = 1 1 1 rise_time = 1.6400 peak_time = 3.6300 max_overshoot = 0.1630 settling_time = 5 >> /**** prog2_1.m *****/ % This program is to find gm & pm from bode num=input('enter numerator of the transfer function=') den=input('enter denominator of the transfer function=') sys=tf(num,den) bode(sys) [gm,pm,wcg,wcp]=margin(sys) Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 63 >>prog2_1 enter numerator of the transfer function=[1 2] num = 1 2 enter denominator of the transfer function=[1 2 5 2 3] den = 1 2 5 2 3 Transfer function: s + 2 ----------------------------- s^4 + 2 s^3 + 5 s^2 + 2 s + 3 gm = 1.2361 pm = 4.9632 wcg = 1.2720 wcp = 1.1940 >> %polar plot num=input('numerator=') den=input('den=') w=0.5:0.01:1.15; [re,im,w]=nyquist(num,den,w); %convert polar coordinates into rectangular coordinates by defining %z,r,theta z=re+i*im; r=abs(z); theta=angle(z); polar(theta,r) /************************************/ /**** prog3_1.m***/ num=input('numerator of transfer function=') den=input('denominator of transfer function=') [r,k]=rlocus(num,den); rlocus(num,den) m=size(r) n=length(k) p=m(1,2) for i=1:n for j=1:p if real(r(i,j))>0 break; k=1; end end end if(k==1) Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 64 disp('given system is stable') else disp('given system is conditionally stable') end >> prog3_1 numerator of transfer function=[0 0 0 1] num = 0 0 0 1 denominator of transfer function=[1 4 5 0] den = 1 4 5 0 / * ** prog3_2.m ***/ num=input('numerator of the transfer function=') den=input('denominator of the transfer function=') sys=tf(num,den) bode(sys) [gm,pm,wcg,wcp]=margin(sys) if (gm<0)|(pm<0) disp('given system is unstable') else disp('given system is stable') end >> prog3_2 numerator of the transfer function=[0 9 1.8 9] Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 65 num = 0 9.0000 1.8000 9.0000 denominator of the transfer function=[1 1.2 9 0] den = 1.0000 1.2000 9.0000 0 Transfer function: 9 s^2 + 1.8 s + 9 ------------------- s^3 + 1.2 s^2 + 9 s gm = Inf pm = 96.5548 wcg = NaN wcp = 9.7492 given system is stable >> Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 66 /**** Prog4.m ***/ choice=input('enter "1" for conversion of i/o model to state variable model and "2" for vice versa') if (choice==1) num=input('numerator of transfer function=') den=input('denominator of transfer function=') [a,b,c,d]=tf2ss(num,den) elseif (choice==2) a=input('system matrix a=') b=input('input matrix b=') c=input('output matrix c=') d=input('transformation matrix d=') [num,den]=ss2tf(a,b,c,d) end > prog4 enter "1" for conversion of i/o model to state variable model and "2" for vice versa1 choice = 1 numerator of transfer function=[1 1] num = 1 1 denominator of transfer function=[1 2 5 9] den = 1 2 5 9 a = -2 -5 -9 1 0 0 0 1 0 b = 1 0 0 c = 0 1 1 d = 0 >> / *** prog3_3.m Nyquist plot ***/ num=input('numerator of transfer function=') den=input('denominator of transfer function=') sys=tf(num,den); nyquist(sys) [gm,pm,wcg,wcp]=margin(sys) if (gm<0)|(pm<0) Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 67 disp('given system is unstable') else disp('given system is stable') end >> prog3_3 numerator of transfer function=[0 0 1] num = 0 0 1 denominator of transfer function=[1 0.8 1] den = 1.0000 0.8000 1.0000 gm = Inf pm = 68.8999 wcg = Inf wcp = 1.1662 given system is stable >> Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 68 SIMULINK What is Simulink? • Simulink is a software package for modeling, simulating, and analyzing dynamical systems. It supports linear and nonlinear systems, modeled in continuous time, sampled time, or a hybrid of the two. Systems can also be multirate, i.e., have different parts that are sampled or updated at different rates. • It is a software package that enables to model, simulate, and analyze dynamic systems, that is, systems whose outputs and states change with time. Simulink can be used to explore the behavior of a wide range of real- world systems, including electrical circuits, shock absorbers, braking systems, and many other electrical, mechanical, and thermodynamic systems. • For modeling, Simulink provides a graphical user interface (GUI) for building models as block diagrams, using click-and-drag mouse operations. This is a far cry from previous simulation packages that require formulating differential equations and difference equations in a language or program. • Simulink includes a comprehensive block library of sinks, sources, linear and nonlinear components, and connectors. Also it can be customized and create new blocks. • Simulating a dynamic system is a two-step process with Simulink. o First, Simulink's model editor used to create a model of the system to be simulated. The model graphically depicts the time-dependent mathematical relationships among the system's inputs, states, and outputs. o Then, Simulink used to simulate the behavior of the system for a specified time span. • To start Simulink, first start MATLAB, then start Simulink in two ways: 1. Click on the Simulink icon on the MATLAB toolbar. 2. Enter the simulink command at the MATLAB prompt. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 69 Modeling Dynamic Systems • Simulink provides a library browser that allows us to select blocks from libraries of standard blocks and a graphical editor that allows us to draw lines connecting the blocks and we can model virtually any real-world dynamic system by selecting and interconnecting the appropriate Simulink blocks. Block Diagrams A Simulink block diagram is a pictorial model of a dynamic system. It consists of a set of symbols, called blocks, interconnected by lines. Each block represents an elementary dynamic system that produces an output either continuously (a continuous block) or at specific points in time (a discrete block). The lines represent connections of block inputs to block outputs. Every block in a block diagram is an instance of a specific type of block. The type of the block determines the relationship between a block's outputs and its inputs, states, and time. Blocks Blocks represent elementary dynamic systems that Simulink knows how to simulate. Simulating Dynamic Systems • Simulating a dynamic system refers to the process of computing a system's states and outputs over a span of time, using information provided by the system's model. • Simulink simulates a system when we choose Start from the model editor's Simulation menu, with the system's model open. • Simulation of the system occurs in two phases: model initialization and model execution. Model Initialization Phase During the initialization phase, Simulink: • Evaluates the model's block parameter expressions to determine their values. • Flattens the model hierarchy by replacing virtual subsystems with the blocks that they contain. • Sorts the blocks into the order in which they need to be executed during the execution phase. • Determines signal attributes, e.g., name, data type, numeric type, and dimesionality, not explicitly specified by the model and checks that each block can accept the signals connected to its inputs. Dr. N. Yadaiah, Dept. of EEE, JNT University, Hyderabad,
[email protected] 70 • Simulink uses a process called attribute propagation to determine unspecified attributes. This process entails propagating the attributes of a source signal to the inputs of the blocks that it drives. • Determines the sample times of all blocks in the model whose sample times we did not explicitly specify. Allocates and initializes memory used to store the current values of each block's states and outputs.