* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Matlab Notes for Student Manual What is Matlab?
Linear least squares (mathematics) wikipedia , lookup
Laplace–Runge–Lenz vector wikipedia , lookup
Jordan normal form wikipedia , lookup
Vector space wikipedia , lookup
Determinant wikipedia , lookup
Eigenvalues and eigenvectors wikipedia , lookup
Matrix (mathematics) wikipedia , lookup
Euclidean vector wikipedia , lookup
System of linear equations wikipedia , lookup
Covariance and contravariance of vectors wikipedia , lookup
Orthogonal matrix wikipedia , lookup
Principal component analysis wikipedia , lookup
Perron–Frobenius theorem wikipedia , lookup
Non-negative matrix factorization wikipedia , lookup
Singular-value decomposition wikipedia , lookup
Cayley–Hamilton theorem wikipedia , lookup
Gaussian elimination wikipedia , lookup
Ordinary least squares wikipedia , lookup
Matrix multiplication wikipedia , lookup
Matlab Notes for Student Manual What is Matlab? - Stands for Matrix Laboratory - Used for programming, 2D & 3D graphing, data analysis, and matrix manipulation There are two primary windows in Matlab, the Command Window and the Edit Window: - Command Window: This window can be used to type in commands and obtain immediate results. The output for Matlab will appear in this screen. - Edit Window: Use this window to create m-files. M-files are used to create programs. To access this window, click on: File > New > m-file Accessing Help - For general help, either type helpwin in the command screen, or click on Help > Help Window in either the command window or the edit window. If you know the name of the command that you need help with, type help FunctionName in the Command Window. Ex: typing » help cos in the command window will produce the following output: COS - Cosine. COS(X) is the cosine of the elements of X. Another source of help in Matlab is under Help > Examples and Demos. Here you will find demonstrations of how to perform various commands. In the Lecture Support and Lab Support sections in WebCT, you will also find additional help material. Script Files vs Functions • A Matlab script file is a text file that contains a sequence of Matlab commands. Using a script file is equivalent to typing in a series of commands at the Matlab command prompt, except that you don’t need to type the commands each time you wish to use them. A script file can only execute commands and cannot accept input. Therefore, any variables/values that you want to use must be declared as part of the script. Running a script m-file - In order to run an m-file, save it, then click on Tools > Run. - If you are using a version of Matlab older than Matlab 6, you might have to change the file path in order to run an m-file. In the Editor window, click on View > Path Browser. Then, click on Browse and choose the directory where your saved m-file is stored. Ex: write a script file that will find the difference between two numbers: Number1 = 10; Number2 = 3; Difference = Number1 - Number2 will produce the following output in the command window: Difference = 7 In order to change the values used in a script file, you need to change the designated variables. • A Matlab function is actually a sub program that can accept input. You are essentially creating a file that is called in the same manner as a predefined function such as sin(x), or mean(x). A function must begin with a statement such as this: function thisfunc(arg1, arg2) where: the name of the function, thisfunc, must be the same as the saved m-file name, and will be used to call upon the function. if there are any arguments to the function, they appear within parentheses after the function name. the word function indicates that this is a function A function can be called from another script file or function, however, for our purposes, typing in the function name and entering values at the command window will be sufficient. Be sure that, as with script files, the correct file path is set, and that your function has been saved before running it. Ex: create a function that takes in 3 values, and finds their sum: function findsum(Number1, Number2, Number3) TheSum = Number1 + Number2 + Number3 Now, typing » findsum(10, 32, 4) produce the following result: at the command window will TheSum = 46 The advantage to using a function for this type of problem is that the numbers entered can vary each time you call the function. However, remember that the number of arguments in the calling statement (in the command window) has to be the same as the number of arguments in the function m-file. Initializing an m-file - Before you begin an m-file, you should initialize it to be sure that all of the variables are cleared etc… using the following three commands. clear all; % resets/removes all previous variables close all; % closes any previously opened windows for figures and % graphs clc % clears any output that was in the command window Commenting - Use the % operator (%) before any line that you wish to comment out. - Any commented text is ignored when Matlab runs an m-file. - Use comments to clarify code and describe what is occurring. - Commented code will appear in green. The Semicolon (;) - Follows commands or scalar/vector/matrix assignments that you don’t want printed to the screen. Ex: Number = 5; %The scalar Number is assigned the value 5, but nothing is % displayed Number = 5 %Number is assigned the value 5, and Number = 5 is displayed % in the command window sum(AVector); %The sum of the elements in AVector are calculated, but % nothing is displayed sum(AVector) %The sum of the elements in AVectore are calculated, and % the sum will be displayed in the command window Displaying Values in the Command Window - If you are displaying values stored in variables, you can simply omit the semicolon at the end of the statement in the Edit Window. - If you’re displaying text: disp(x) - X can be text or a variable or a command. - If x is text, then the desired text should be enclosed by single quotes Ex: disp(‘It tastes like burning’) % It tastes like burning is % displayed in the command window disp(AVariable) % the value stored in AVariable will be displayed in % the command window disp(max(AVector) %the largest value in AVector will be displayed in %the command window - Don’t forget to omit the ; at the end of the disp statement so that the result of the command can be output. You can change the length of the decimal places that are displayed using format long or format short format long will set the number format for long decimals and format short will set the numbers displayed for short decimals. Initializing/Assigning Variables (Scalars) - All Scalar/Vector/Matrix assignments are made in the Edit Window - Only numeric values can be assigned to variables - To assign a value to a scalar variable, type in the variable name, and equal sign, then the value that you wish to assign to the variable: ANumber = 18; The previous command assigns the value 18 to the scalar ANumber. Now, ANumber can be used in commands and expressions instead of the value 18. Ex: Number = 5; % Assigns the value 5 to the scalar Number disp(Number) % Displays the value 5 on the screen Number = Number + 3 % Takes the value stored in Number (5), adds 3, % then reassigns the new value to Number (8) and % displays the result in the command window. Creating/Initializing A Vector or a Matrix There are many vector and matrix manipulation commands in Matlab, and they can also be extensively used in data analysis. Vectors When declaring vectors, use the semicolon to separate each element in the vector: AVector = [Value1; Value2; Value3; Value4; ValueN]; Ex: StudentMarks = [89;96;63;74;85] will produce: 89 96 63 74 85 in the command window. Matrices - separate the rows of the matrix with a semicolon. AMatrix = [Value1, Value2, Value3; Value4, Value5, Value6]; Ex: StudentMarks = [89, 96, 63; 74, 85, 32] will produce: - 89 96 63 74 85 32 in the command window Another way to initialize matrices is to use new lines instead of semicolons to designate a new row in the matrix. This can be advantageous as it lets you visualize how the matrix will be displayed: StudentMarks = [89, 96, 63 74, 85, 32] this will have the same output effect as using semicolons to change the current row. - Matrices and Vectors can be any size, although a vector can only have one column or one row. If you don’t use a semicolon after a vector/matrix declaration, the matrix will be displayed in the command window. Scalar Operations - Basic mathematical operations work on scalars in Matlab. • + • • * • / - these operators can be used on numbers, or scalar variables. Ex: Number1 Number2 Number3 Number4 - = = = = 8; 2; Number1*3 (Number1 - Number2) * Number3 brackets ( ) and order or operations apply in all of these types of calculation Trigonometric Functions • • • • • • sin(x) cos(x) tan(x) these three commands return the sin/cos/tan of an angle (x) asin(x) acos(x) atan(x) - these three commands return the angle that corresponds to the sin/cos/tan given(x) - Angles need to be given in radians for the formulas to work. to convert from degrees to radians: AngleInDegrees * pi/180; Data Analysis Tools - all of the following data analysis commands are used with vectors or matrices. Again, the semicolon has the same effect as before for displaying values. • max(x) and min(x): These commands return (respectively) the largest or smallest values in a given vector x. If x is a matrix, then max(x) and min(x) will find the largest or smallest value in each column of the matrix x, and will output a row vector containing the values. Temperatures = [29;22;25;31;38;25;26;27]; min(Temperatures) will output the smallest value in Temperatures 22 • mean(x) and median(x): These commands return (respectively) the average value or the median value in a given vector x or matrix x. If x is a matrix, then each of these commands will output a row vector containing the mean or median value from each column in the matrix. Rainfall = [250, 123,164;198,220,172;198,231,182] Rainfall = median(Rainfall) 250 198 198 123 220 231 164 172 182 will output the median from each column of the matrix Rainfall: 198 220 172 • sum(x) and product(x): These commands act in the same way as the previous four, except they calculate the sum or the product of a vector x or of each of the columns of a matrix x, output in a row vector. • sort(x): this command sorts the values of the given vector x in ascending order. If x is a matrix, then this command will sort each column of the matrix independently. Temperatures = [29;22;25;31;38;25;26;27]; sort(Temperatures) will output the sorted vector Temperatures: 22 25 25 26 27 29 31 38 • std(x): calculates the standard deviation of a the values in a vector or the columns of a matrix. Acts in the same way as all of the other data analysis commands. • randn(n) and randn(m,n): Develops a set of random Gaussian values. randn(n) will return a n*n matrix, while randn(m,n) will return a m*n matrix. If you wish to return a single set of data (a vector) set m or n to 1 in the randn(m,n) command. Ex: GaussianNumbers = randn(30,1); - will produce a vector that contains 30 random gaussian values. All of the values are stored in the vector GaussianNumbers. GaussianNumbers can then be used as an ordinary vector. A similar command, rand(n) or rand(m,n) acts the same way as randn, but does develop a Gaussian set of data. Each of these commands will produce values between 0 and 1, and randn automatically sets the standard deviation to 1 and the mean to 0. The mean can be altered however: Numbers = randn(45,2) + 5; - will produce a 45 * 2 matrix that contains a set of gaussian data, with a standard deviation of 1 and a mean of 5 Every set of regular random numbers is never truly “random” however. You can specify the seed of random numbers that you want the computer to use. Every seed will produce its own set of numbers, and can be changed using the - command, where n is the number of the seed that you wish to use. with Gaussian random numbers, you don’t need to specify the seed, as the data will fluctuate slightly every time the program is run. rand(‘seed’, n); • mod(x,y): This command will return a whole number remainder when the value in x is divided by y. This can be very useful when determining if a number is even or odd. To determine if a number x is even, enter a y value of 2 into the mod command. The result should be 0. If the number is odd, then the result should be 1. This command operates in the same manner as the rem(x,y) command. Ex: mod(38, 2) mod(13, 2) Solution: ans = 0 ans = 1 Graphing • plot (x,y) - this will plot an x vs y graph, where x and y will normally be vectors or matrices. - plot(Vector1, Vector2) -> Vector1 has the x-axis values and Vector2 has the y-axis values. - You can also plot more than one set of data on the same graph: plot(x1, y1, x1, y2) this is very useful when comparing graphs. Ex: Vector1 = [1;2;3;4]; Vector2 = [2;9;4;12]; Vector3 = [10;3;8;0]; plot(Vector1, Vector2, Vector1, Vector3) will produce the following graph: -You could also set y to a matrix. If the command plot(Vector1, AMatrix) was performed, each column of the matrix would act as a separate set of data and multiple plots will be created on the same graph with the same effect as plotting more than one vector on the same graph. -To place labels on a graph, enter the following in your m-file: xlabel(‘x-label name’), ylabel(‘y-label name’) -To place a title on a graph: title(‘Enter Title Here’) •hist(x, n) -this will create a histogram. Similar to Excel, this command will create a histogram with data divided into bins (n). x will be either a vector containing data, or a scalar that contains random numbers, particularly Gaussian random numbers. Ex: -hist(GaussianData, 30) will plot a histogram using the data stored in GaussianData, and will divide the data into 30 different bins. You can increase the accuracy and resolution of your graph by increasing the number of different data bins that the values can be placed into. The Colon Operator (:) -can be used to create vectors and subsets of matrices •to create regularly spaced vectors: -j:k [j, j+1, j+2, …k] -j:k is empty if j > k -j:i:k [j, j+i, j+2i, j+3i, … k] -j:i:k is empty if i>0 and j>k or if i<0 and j<k Ex: x = 2:7; y = 2:3:14; disp(x) disp(y) R=[4,6,5 12,6,7 1,3,11 8,9,3 13,6,2]; will produce 2 3 4 5 6 7 as ouput will produce 2 5 8 11 14 as output •selecting subsets of vectors and matrices -you can refer to the elements of an array or vector by using brackets and colons. -Accessing an element is easy, as you only need to specify and element: AVector (Element) Ex: AVector(17) refers to the 17th element in the vector AVector -When accessing the elements of an array, you have to specify a row and a column: AMatrix (row, column) where the first entry in the brackets will refer the row and the second entry will refer to the column of the matrix. Ex: R(2,3) refers to the element at the intersection of the 2nd row and the 3rd column of the matrix R (above), which would return a value of 7 R(4, :) refers to the fourth row of R R(:, 2) refers to the 2nd column of R 8 9 3 6 6 3 9 6 -And, the colon operator can also be used as it was when creating evenly spaced vectors: Ex: R(1:3, 2:3) will create a subset of the matrix R that goes from the first to the third row, only with the 2nd to fifth column: 65 67 3 11 - You can also specify the amount to go up or down by with the colon operator, as before. Ex: R(1:2:5, :) will produce a subset of R, that starts at the first row of R and goes to the 5th row of R, only in increments of 2 however. The 1st, 3rd, and 5th rows of R will then be displayed. 465 1 3 11 13 6 2 - R(:, :) will return the same thing as R R(:) will return all of the elements in R seen as a single column Practice Problems Write out the contents of each of the following matrices. Refer to the matrix R R=[4,6,5 where necessary. The answers can be verified in Matlab. 12,6,7 1,3,11 A = R(:,1) 8,9,3 Q = [1:3;4:6] T = -0.5:0.1:0.5 13,6,2]; N = R(3:5,1:2) X = R(2:4,1:2:3) Solutions A= 4 12 1 8 13 Q= 1 4 N= 2 5 3 6 1 8 13 X= 3 9 6 12 7 1 11 8 3 T = -0.5000 -0.4000 -0.3000 -0.2000 -0.1000 0 0.1000 0.2000 0.3000 0.4000 0.5000 \\\ Selection and Looping Relational and Logical Operators: - these operators are very useful when comparing and choosing values in if statements and in loops. - They are used to determine if an expression will evaluate to true or false. If an expression evaluates to true, Matlab will return 1 in the command window. Otherwise, the expression evaluated to false, and Matlab will return a 0. • < <= > >= == ~= less than less than or equal to greater than greater than or equal to equal to not equal to ~ & | not and or if statements - if statements are logical expressions. If the logical expression is true, then the statements between the if statement and the end statement are executed. If the logical expression is false, then the program will skip the actions inside of the if statement and jump to the statement immediately after the end statement. if expression statements end -you can have any number of commands in the statements section, and semicolon rules still apply to these commands. Ex: If the given number is greater or equal to 50, then increase the counter by one and display the number that is being tested: if Number >= 50 count = count + 1; disp(Number) end • while loop - used to repeat a set of commands as long as the specified condition/ expression remains true. while expression statements end - - The loop tests the condition before the actions are performed. Therefore, if the expression evaluates to false, no actions are performed. The end command signifies the end of the loop, which is where the program will go back to the beginning of the loop to re-evaluate the expression. You can have any number of commands inside the while loop. Ex: Find the smallest odd number whose cube is greater than 3000. clear all; close all; clc %The previous 3 commands will initialize the program Number = 1; %Sets the first odd number to be tested to 1 CubedNumber = Number*Number*Number; %Calculates the first cubed value, as the while loop is a pre-test %loop and needs a value to test before you can enter the loop while (CubedNumber < 4500) %this expression will test the value of CubedNumber each time the %program executes the loop, until the value of CubedNumber is > 3000 Number = Number + 2; %Increases the value of Number by 2, as you are only testing odd %numbers CubedNumber = Number*Number*Number; %Recalculates the value of CubedNumber, as you need to test the value %again at the beginning of the loop to determine if you will make %another pass. end %From this point, the program will go to the beginning of the loop and %test the value of CubedNumber to see whether or not it is necessary to %do the loop again. disp('The Smallest odd number whose cube is greater than 4500 is:') Number %displays a string, and the smalledst odd number whose cube is greater %than 4500. disp('Its cube is:') disp(CubedNumber) %displays another string, as well as the cubed value that was tested. Here is the output to the program that is displayed in the command window of Matlab. The Smallet odd number whose cube is greater than 4500 is: Number = 17 Its cube is: 4913 Vector/Matrix Operations • Vector Addition/Subtraction: In Matlab, vector addition and subtraction is performed with the same commands as scalar addition/subtraction. The rules for vector addition remain, as the vectors will be added/subtracted element by element. The vectors must have the same dimensions, or Matlab will produce an error message. Ex: Add the following vectors using Matlab: y=[3;4;2;6]; x=[-2;6;9;1]; z=y+x will produce the following output: z= 1 10 11 7 • Dot Product: The dot product operator will calculate the dot product of 2 vectors that have the same number of elements. There are 2 commands that can calculate the dot product of 2 vectors m and n ( ): 1) sum(A.*B) and 2) dot(A,B) Ex: Given the vectors , calculate : d=[5;3;-3]; e=[4;-4;1]; f=dot(d,e) This will produce the following output: f=5 •Cross Product: The cross product operator will calculate the cross product of 2 vectors that each contains 3 elements. Use the cross(A, B) command, where A and B are vectors ( ). Ex: Using the vectors d and e from above, calculate . d=[5;3;-3]; e=[4;-4;1]; z=cross(e,d) will produce the following output: z= 9 17 32 •Scalar – Vector Multiplication: Each element of the vector is multiplied by the scalar: Ex: Given the vector z = , and the scalar z = [6;7;4;5;2;3]; a = 1.61; o = a*z will produce: o= 9.6600 11.2700 6.4400 8.0500 3.2200 , calculate 4.8300 • Matrix-Matrix Addition/Subtraction: Uses the + operator and works as before, where each matrix must have the same size. Ex: a=[1,2,3;4,5,6;7,8,9]; b=[2,3,4;5,6,7;8,9,10]; c=a+b will produce: c= 3 5 7 9 11 13 15 17 19 • Matrix Transpose: This command uses the ‘ operator at the end of a matrix name to transpose the matrix. You can display the transpose of a matrix, assign it to another variable, or use the transpose directly in matrix operations. Ex: J=[1,3,5 7,9,11]; Q=J’ J’ The two commands to display the transposed matrix will produce the same output: 1 7 3 9 5 11 • Matrix-Matrix Multiplication: This performs the multiplication of two matrices, according to the normal rules for multiplying matrices. If the inner dimensions of the matrices must be equal or Matlab will produce an error message. When multiplying 2 matrices in Matlab, use the operator, as you would to multiply 2 scalars together. Ex: Multiply and together according to t=m*c m=[5,3,-3;4,-4,1]; c=[0,-2;4,5; 2,-3]; t=m*c will display the resulting matrix t: t= 6 * 14 -14 -31 •Solutions to systems of linear equations: - Using Matlab, you can solve systems of linear equations. Simply take a given matrix, and enter the matrix A, as well as the vector b into Matlab. To find the solution x, use the left division operator: \ . Ex: The following system of three equations in three unknowns This produces , the vector and the unknown Now, to solve the equation for x, use the \ operator in the equation . A=[3,2,-1;-1,3,2;1,-1,-1]; b=[10;5;-1]; x=A\b This will produce: - x= -2.0000 5.0000 -6.0000 as output. If a system of equations does not have a unique solution, an error message will be displayed or Matlab will produce a matrix whose elements are “inf”. 1. Add or subtract the following vectors according to the given expression: a) b) c) 2. Using the vectors j, k, and l from the previous section, calculate the following dot products using Matlab: a) b) c) Use the following matrices for questions 3 and 4: 3. Perform the following matrix operations in Matlab: a) b) c) d) e) f) g) 4. Transpose the following matrices: a) b) c) d) 5. Solve the following systems of equations using Matlab a) b) c) d) e) The above can be described by three equations with three unknowns. Using KVL and Ohm’s law, we have: Loop #1: Loop #2: Loop #3: Solutions: 1. a) 2. a) 20 3. a) b) c) b) –17 c) –4 b) c) Can’t be done. The dimensions don’t correspond d) Can’t be done. The dimensions don’t correspond e) f) g) 4. a) b) c) d) 5. a) b) There isn’t a unique solution c) d) e) MATLAB solution: » A = [12 -2 0; -2 13 -6; 0 -6 7]; » b = [5; 0; 0]; » x = A\b x= 0.4351 0.1108 0.0949