230 likes | 368 Views
MATLAB. MATrix LABoratory. MATLAB Desktop. Command window – input and output Command history – records commands given in the command window
E N D
MATLAB MATrix LABoratory
MATLAB Desktop • Command window – input and output • Command history – records commands given in the command window • Current directory – the directory where MATLAB looks for user-created functions. If a function is not in the current directory, MATLAB will look in the folders defined in Files->Set Path
Variables • Variables are used to store information (scalar, vector, matrix, string, etc.) • Variable names are composed of any string of alphanumeric characters (first character must be a letter). Names are case-sensitive. The isvarname function can be used to test if a name is valid as a variable name. • Variable names override functions; therefore, function names should not be used as variable names. • Variables are assigned values with the assignment operator ‘=‘ • The variables in the workspace can be listed with the who and whos functions • All currently defined variables can also be seen in the workspace browser.
Variables (cont.) • Variables can be removed from the workspace with the clear function. • Workspace variables can be stored to disk with save and retrieved with load. • Variables can also be renamed, deleted, or edited (vectors & matrices only) in the workspace browser. • There are several variables the system uses. The user can call them for use in calculations. Some of these are: • pi • eps – contains the value of the machine precision • ans – if a function or calculation is called without assigning the result into a variable, the result is placed in ans.
Matrices and Other Structures • The basic structure in MATLAB, a matrix is a rectangular (two-dimensional) structure with m rows and n columns. • If either m or n equals 1, the structure is known as a vector. If m=1, it is a row vector; if n=1, it is a column vector. • If m=n=1, the structure is known as a scalar. • If m or n equal 0, the structure is known as an empty matrix. • If the number of dimensions is greater than two, the structure is known as an array. • The number of dimensions of an array or other structure can be determined with the ndims function. • size(A) returns a vector containing the number of elements along each dimension of structure A. size(A,n) returns the length of the nth dimension of A. • length(A) returns the length of the largest dimension of A (i.e. the largest number in the vector produced by size(A).
Creating Matrices • Directly • i:j:k creates a row vector whose elements run from i to k at intervals of j. If j is omitted, it is assumed to be 1. • [a,b,c] creates a row vector whose elements are a, b, and c • [a;b;c] creates a column vector whose elements are a, b, and c. • [[a,b,c];[d,e,f]] creates a 2x3 matrix. Spaces and carriage returns can also be used instead of commas and semicolons, respectively. • With a function, such as • ones • zeros • eyes • rand • magic
Matrix Subscripts • A(m,n) will return the element at row m and column n of matrix A • A(m) will return the m-th element of the column vector resulting from stacking all of A’s columns • The colon operator: • A(m,:) will return a row vector with the m-th row of A • A(:,n) will return a column vector with the n-th column of A • A(i:j,m) returns a column vector containing the elements of rows i-j in column m of A. • A(i,m:n) returns a row vector containing the elements of columns m-n in row i of A. • A(i:j,m:n) returns a matrix containing the elements in rows i-j of columns m-n of A. • The colon operator can be used in more complex forms; for example, A(2:2:end,:) will return the even-numbered rows of A. • The keyword end designates the last row or column of the matrix. • Elements meeting certain conditions can be retrieved with logical functions such as find or isfinite.
Manipulating Matrices • Concatenation: matrices can be joined together with the comma and semicolon operators. The resulting matrix must be rectangular. • Transposition: The apostrophe operator causes a complex conjugate transposition of the matrix (e.g. A’). • Deleting rows and columns: rows or columns can be deleted by using []. For example, A(:,2)=[] will delete column 2 of A. The resulting matrix must be rectangular.
Matrix Mathematical Functions – element-by-element operations • Element-by-element operations function on two vectors, matrices, or arrays of equal size. • The operation is performed between each element in the first structure and the element in the same position in the second structure. The result is a structure of the same size. • Element-by-element operators can also be used between two scalars or a scalar and a structure. In the latter case, the operation is performed between each element in the structure and the scalar, and the result is a new structure equal in size to the first. For example, 1+B, where B is a 2x2 matrice, will result in a 2x2 matrix. • Element-by-element operators include: • + - addition • - - subtraction • .* - multiplication • ./ - right division (element on the left of the operator is divided by that on the right) • .\ - left division (element on the right of the operator is divided by that on the left) • .^ - element-by-element power • Element-by-element operations are sometimes called array operations
Matrix Mathematical Functions – matrix arithmetic operations • Matrix arithmetic operations function according to the rules of linear algebra. • Matrix arithmetic operators include: • * - matrix multiplication. This operator multiplies a jxk matrix by an mxn matrix. k must be equal to m. • / - matrix right division. X=B/A is the solution to X*A=B. • \ - matrix left division. X=A\B is the solution to A*X=B. • ^ - matrix power. This operator only functions between a matrix and a scalar (or vice versa). The matrix must be square. • These operators can also be used between two scalars or a scalar and a structure, in which case they operate the same as their element-by-element equivalents.
Other Algebraic Operations • MatLab has a variety of functions for performing algebraic operations. • For the most part, these function only with vectors and matrices. • Such functions include: • ‘ – matrix transpose. This function transposes an mxn matrix (or vector) into an nxm matrix. If any elements are complex, they are replaced by their conjugates. • .’ - array transpose. This operator functions in the same way as the matrix transpose operator, except that complex elements are not conjugated. • diag(A,n) – returns the nth diagonal of matrix A. If n is unspecified, the main diagonal is returned. • eig(A) – returns the eigenvalues of A • det(A) – returns the determinant of A • poly(A) – finds the coefficients of the characteristic polynomial of A
Solving Systems of Linear Equations • The matrix division operators can be used to solve systems of linear equations.
Solving Systems of Linear Equations (cont.) • The method above assumes that A has an inverse matrix – this means the system has a unique solution. An inverse matrix exists when the determinant of A≠0. • If the matrix is singular – that is, its determinant is 0, or alternatively its rank (the number of linearly independent rows or columns) is smaller than the number of equations – and rank([A B])≠rank(A) than the system has no solution. • If the matrix is singular and rank([A B])=rank(A), then the system has an infinite number of solutions.
Scalar Functions • Scalar functions are functions (usually mathematical) whose input is a single number. • If used on a vector or a matrix, these functions evaluate it element-by-element, returning a vector or matrix of the same size. • Such functions include: • sin(a) and similar trigonometric functions (cos, asin, etc). The input (or output, for inverse functions) of these functions is in radians. • exp(a) – exponent • Floor(a), ceil(a), and round – round a number down, up, or mathematically, respectively. • abs(a) – returns the absolute value of a. • sqrt(a) – returns the square root of a. • sign(a) – returns -1 for negative numbers or 1 for positive numbers/zero.
Scalar Functions (cont.) • Some scalar functions operate on two scalars. If one or both inputs are vectors, matrices, or arrays, an element-by-element operation is performed instead. If both inputs are vectors, matrices, or arrays, both must be the same size. • Such functions include: • mod(x,y) – returns the result of x modulus y • atan2(x,y) – calculates a four-quarter inverse tangent. It calculates the inverse tangent of y/x, but the sign of the result depends on the signs (not just the relative signs, as with the normal atan function) of x and y – in other words, in what quarter the point is located.
Vector functions • These functions usually accept a vector as input. • If an n-dimensional array (such as a matrix) is used instead, the function will be carried out along the first dimension. In the case of a matrix, the result will (usually) be a vector; in the case of an array, the result (usually) will be an n-dimensional array with a first dimension of length 1. • Such functions include: • sum(a) – sums the elements of the vector a. • sort(a) – returns a vector the same size as a, with the elements of a sorted in ascending order.
Multi-Output Functions • Some functions return two or more values. • If only the function is assigned to a single variable, or no variable, only the first value is returned. • An appropriate number of variable in brackets must be used to get the other values. • For example: the max(a) function returns the maximum value among the elements of the vector a, and the index of that maximum value in the vector. b=max(a) will only return the first value (the value of the largest element). In order to retrieve the index value, the proper format is [b,c]=max(a); in this case, the size of the largest value will be stored in b, and its index will be stored in c. • If two many variables are used, an error will occur .
Complex Number • Complex numbers can be formed using the i function, as in a=x+y*i. • j can be used instead i. • If I or j are being used as variables in the workspace, they cannot be used to form complex numbers. • Complex numbers can also be formed using the complex function. a=complex(x,y) is the same as a=x+i*y. • There are several functions operating with complex numbers, such as: • abs(a) – returns the absolute value of complex number a. • angle(a) – returns the phase angle of a. • conj(a) – returns the complex conjugate of a.
Calculus Functions (examples) • gradient – returns a vector or matrices (depending on the input) with the gradient of the input structure (the amount of output arguments depends on the number of dimensions of the input – each output is the gradient in a specific direction). • curl – calculates the curl (rotor) of a vector field (vector fields are input as multiple matrices or arrays, one for each dimension; for example, a 2D vector field would be input as two matrices, one containing the x-axis vector magnitudes and one containing the y-axis magnitudes).. • divergence – calculates the divergence of a vector field. • quad – numerically calculates an integral.
Structure Arrays • A structure array is a special type of data structure, where a single element in the array contains several data values. • Each element in the array contains one or more fields. A field is a value that has a name. • A.first=1 creates a new structure array called A which has a field called first, whose value (for the first element in the array) is 1. • A(2).first=4 adds another element to the array; the value of its “first” field is 4. • A(2).second=‘one’ adds a second field to each of the elements in the array, and assigns the text value “one” to that field in the second element. When a new field is added to an element in the array, all the other elements in the array receive a new, empty field. After the previous paragraph, A(1) now has a “second” field who’s value is an empty array. Note that the values assigned to the same fields in different elements need not be the same type; for example, A(1).second could be assigned a string or a matrix. • The fieldnames function returns the names of the fields of a structure array. • Elements can be removed from a structure by assigning an empty array (e.g., A(2)=[]) or with the rmfield function. • Structures can also be created using the struct function.
Structure Arrays (cont.) • Structure arrays are useful to create collections of data where each data element is associated with several pieces of data. For example, the results of a test could be stored, with each element containing a field with name of a particular student and a field with his test score. • Thought should be given into how to arrange the data in a structure. Consider the example of an mxn pixel RGB image. • One way to organize the image data is as a single-element structure array with three fields (red, green, and blue); each field contains a matrix with the red, green, and blue images respectively. • Alternatively, the data can be arranged in a structure matrix, with each element representing a pixel, and each elements fields represent the red, green, and blue values for that particular pixel. • The first method is preferable if it is desirable to extract the entire green image (for example). Also, if there is more than one image, each can be represented by a separate element in the array. However, if a subsection of the image is desired, the red, green, and blue portions of the image ,ust be extracted separately. The second method is more convenient for extracting subsections, but showing the image is more involved.
Cell Array • A cell array is a data structure, each element of which can be a different type. • Cell arrays can be created by assignment. For example, the statement A{1,1}=1:4 will create a cell matrix, with the vector [1,2,3,4] at position (1,1). Entering subsequently A{2,1}=‘three’ will add a string element to the matrix at position (2,1). • Another way to use assignment is like a normal matrix. The result from the example above could also be obtained with A={[1:4];’three’}. • Cell arrays can also be constructed with the cell function.
String Manipulation • Strings are created by assigning a string, enclosed in single quotes (‘) to a variable. • MatLab handles strings as arrays of characters; they can be concatenated like vectors, and subsections can be extracted in a similar fashion. • The num2str function converts numerical data to a string.