MECH 241: Computational Techniques in Mechanical engineering Linear Algebra : Macole Sabat, Ph.D. Relational Operators • Relational operators compare the elements in two arrays and return logical true or false values to indicate where the relation holds. == >= > <= < ~= isequal isequaln Determine equality Determine greater than or equal to Determine greater than Determine less than or equal to Determine less than Determine inequality Determine array equality Determine array equality, treating NaN values as equal Mc. Sabat , MECH 241, UoB 2 Logical Operation • The logical data type represents true or false states using the numbers 1 and 0, respectively. Certain MATLAB® functions and operators return logical values to indicate fulfillment of a condition. • One can use those logical values to index into an array or execute conditional code. Mc. Sabat , MECH 241, UoB 3 Logical Operation Short-circuit &&, || & ~ | xor all any false find islogical logical true Logical operations with short-circuiting Find logical AND Find logical NOT Find logical OR Find logical exclusive-OR Determine if all array elements are nonzero or true Determine if any array elements are nonzero Logical 0 (false) Find indices and values of nonzero elements Determine if input is logical array Convert numeric values to logicals Logical 1 (true) • With logical short-circuiting, the second operand is evaluated only when the result is not fully determined by the first operand. • Due to the properties of logical AND and OR, the result of a logical expression is sometimes fully determined before evaluating all of the conditions. Mc. Sabat , MECH 241, UoB 4 Operators Precedence • One can build expressions that use any combination of arithmetic, relational, and logical operators. • Precedence levels determine the order in which MATLAB® evaluates an expression. • Within each precedence level, operators have equal precedence and are evaluated from left to right. Mc. Sabat , MECH 241, UoB 5 Operators Precedence • The precedence rules for MATLAB operators are shown in this list, ordered from highest precedence level to lowest precedence level: 1. Parentheses () 2. Transpose (.'), power (.^), complex conjugate transpose ('), matrix power (^) 3. Power with unary minus (.^-), unary plus (.^+), or logical negation (.^~) as well as matrix power with unary minus (^-), unary plus (^+), or logical negation (^~). Note: Although most operators work from left to right, the operators (^-), (.^-), (^+), (.^+), (^~), and (.^~) work from second from the right to left. It is recommended that you use parentheses to explicitly specify the intended precedence of statements containing these operator combinations. Mc. Sabat , MECH 241, UoB 6 Operators Precedence 4. Unary plus (+), unary minus (-), logical negation (~) 5. Multiplication (.*), right division (./), left division (.\), matrix multiplication (*), matrix right division (/), matrix left division (\) 6. Addition (+), subtraction (-) 7. Colon operator (:) 8. Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=) 9. Element-wise AND (&) 10. Element-wise OR (|) 11. Short-circuit AND (&&) 12. Short-circuit OR (||) Mc. Sabat , MECH 241, UoB 7 Operators Precedence • Precedence of AND and OR Operators: – MATLAB always gives the & operator precedence over the | operator. Although MATLAB typically evaluates expressions from left to right, the expression a|b&c is evaluated as a|(b&c). It is a good idea to use parentheses to explicitly specify the intended precedence of statements containing combinations of & and |. – The same precedence rule holds true for the && and || operators. Mc. Sabat , MECH 241, UoB 8 Operators Precedence • Overriding Default Precedence: – The default precedence can be overridden using parentheses ❖Example: A B C C = 3; = 2; = A/B^2 = 0.7500 D = (A/B)^2 D = 2.2500 Mc. Sabat , MECH 241, UoB 9 Array Vs Matrix Operations • MATLAB® has two different types of arithmetic operations: – array operations and – matrix operations. • You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices. • Matrix operations follow the rules of linear algebra. • By contrast, array operations execute element by element operations and support multidimensional arrays. • The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary. Mc. Sabat , MECH 241, UoB 10 Array Operations • Array operations execute element by element operations on corresponding elements of vectors, matrices, and multidimensional arrays. • If the operands have the same size, then each element in the first operand gets matched up with the element in the same location in the second operand. • If the operands have compatible sizes, then each input is implicitly expanded as needed to match the size of the other. Mc. Sabat , MECH 241, UoB 11 Array Operations • The following table provides a summary of arithmetic array operators in MATLAB. For function-specific information, click the link to the function reference page in the last column. Operator + + .* Purpose Addition Unary plus Subtraction Unary minus Element-wise multiplication .^ Element-wise power ./ Right array division .\ Left array division .' Array transpose Description A+B adds A and B. +A returns A. A-B subtracts B from A -A negates the elements of A. A.*B is the element-by-element product of A and B. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A./B is the matrix with elements A(i,j)/B(i,j). A.\B is the matrix with elements B(i,j)/A(i,j). A.' is the array transpose of A. For complex matrices, this does not involve conjugation. Reference Page plus uplus minus uminus times power rdivide ldivide transpose ❖Example: ArrayOpExp.mlx Mc. Sabat , MECH 241, UoB 12 Note of Array Compatibility • Most binary (two-input) operators and functions in MATLAB® support numeric arrays that have compatible sizes. • Two inputs have compatible sizes if, – for every dimension, the dimension sizes of the inputs are either the same or one of them is 1. • In the simplest cases, two array sizes are compatible if they are exactly the same or if one is a scalar. • MATLAB implicitly expands arrays with compatible sizes to be the same size during the execution of the element-wise operation or function. Mc. Sabat , MECH 241, UoB 13 Note of Array Compatibility • 2D inputs: combinations of scalars, vectors, and matrices that have compatible sizes: – Two inputs which are exactly the same size. – One input is a scalar. Mc. Sabat , MECH 241, UoB 14 Note of Array Compatibility • 2D inputs: combinations of scalars, vectors, and matrices that have compatible sizes: – One input is a matrix, and the other is a column vector with the same number of rows. – One input is a column vector, and the other is a row vector. Mc. Sabat , MECH 241, UoB 15 Note of Array Compatibility • 2D inputs: • Inputs with Incompatible Sizes: Incompatible inputs have sizes that cannot be implicitly expanded to be the same size. For example: – One of the dimension sizes are not equal, and neither is 1. A: 3-by-2 B: 4-by-2 – Two nonscalar row vectors with lengths that are not the same. A: 1-by-3 B: 1-by-4 Mc. Sabat , MECH 241, UoB 16 Note of Array Compatibility • Multidimensional Arrays: Every array in MATLAB has trailing dimensions of size 1. For multidimensional arrays, this means that a 3-by-4 matrix is the same as a matrix of size 3-by-4-by-1by-1-by-1. • Examples of multidimensional arrays with compatible sizes: – One input is a matrix, and the other is a 3-D array with the same number of rows and columns. Mc. Sabat , MECH 241, UoB 17 Note of Array Compatibility • Examples of multidimensional arrays with compatible sizes: – One input is a matrix, and the other is a 3-D array. The dimensions are all either the same or one of them is 1. Mc. Sabat , MECH 241, UoB 18 Note of Live Functions • Live functions are program files that contain code and formatted text together in a single interactive environment called the Live Editor. • Similar to live scripts, live functions allow you to reuse sequences of commands by storing them in program files. • Live functions provide more flexibility, though, primarily because you can pass them input values and receive output values. Mc. Sabat , MECH 241, UoB 19 Note of Live Functions • Create Live Function from Selected Code • If you have an existing large live script or function, you can break it into smaller pieces by automatically converting selected areas of code into functions or local functions. This is called code refactoring. • To refactor a selected area of code, select one or more lines of code and on the Live Editor tab, in the Code section, click Refactor. Then, select from the available options. MATLAB creates a function with the selected code and replaces the original code with a call to the newly created function. • You can run live functions using several methods, including calling them from the Command Window or calling them from a live script. • Disadvantage: can’t run function directly and thus won’t visualize it results to the right of the code as in live scirpts. ❖Examples: addmefct.m, addme.mlx, RefactorBaseForExp.mlx Mc. Sabat , MECH 241, UoB 20 Navigate a live script with shortcuts Ctrl + Alt + Enter F5 F10 Shift + F5 Ctrl + Enter Ctrl + Shift + Enter Mc. Sabat , MECH 241, UoB 21 Linear Algebra • Linear algebra functions in MATLAB® provide fast, numerically robust matrix calculations. Capabilities include a variety of: – matrix operations – linear equation solving, – matrix factorizations, – computation of eigenvalues or singular values, and more. Mc. Sabat , MECH 241, UoB 22 Matrices in the MATLAB Environment • The MATLAB environment uses the term matrix to indicate a variable containing real or complex numbers arranged in a twodimensional grid. • An array is, more generally, a vector, matrix, or higher dimensional grid of numbers. All arrays in MATLAB are rectangular, in the sense that the component vectors along any dimension are all the same length. • The mathematical operations defined on matrices are the subject of linear algebra. Mc. Sabat , MECH 241, UoB 23 Matrices in the MATLAB Environment • MATLAB has many functions that create different kinds of matrices, recall zeros, ones • M = magic(n) returns an n-by-n matrix constructed from the integers 1 through n2 with equal row and column sums. The order n must be a scalar greater than or equal to 3 in order to create a valid magic square. • X = randi(imax,sz1,sz2) returns an sz1-by-sz2 matrix of pseudorandom integers between between 1 and imax. Mc. Sabat , MECH 241, UoB 24 Matrices in the MATLAB Environment • I = eye(n,m) returns an n-by-m matrix with ones on the main diagonal and zeros elsewhere: identify matrix. • D = diag(v) returns a square diagonal matrix with the elements of vector v on the main diagonal. • P = pascal(n) returns a Pascal’s Matrix of order n. P is a symmetric positive definite matrix with integer entries taken from Pascal's triangle. The inverse of P has integer entries. Mc. Sabat , MECH 241, UoB 25 Matrices in the MATLAB Environment • Pascal’s triangle is a triangle formed by rows of numbers. The first row has entry 1. Each succeeding row is formed by adding adjacent entries of the previous row, substituting a 0 where no adjacent entry exists. The pascal function forms Pascal’s matrix by selecting the portion of Pascal’s triangle that corresponds to the specified matrix dimensions, as outlined in the graphic. The matrix outlined corresponds to the MATLAB® command pascal(4). Mc. Sabat , MECH 241, UoB 26 Matrices in the MATLAB Environment • The matrix outlined corresponds to the MATLAB® command pascal(4). ❖Example: MatrixCreateExp.mlx Mc. Sabat , MECH 241, UoB 27 Matrix Operations • Matrix operations follow the rules of linear algebra and are not compatible with multidimensional arrays. • The required size and shape of the inputs in relation to one another depends on the operation. • For nonscalar inputs, the matrix operators generally calculate different answers than their array operator counterparts. • For example, if you use the matrix right division operator, /, to divide two matrices, the matrices must have the same number of columns. But if you use the matrix multiplication operator, *, to multiply two matrices, then the matrices must have a common inner dimension. That is, the number of columns in the first input must be equal to the number of rows in the second input. Mc. Sabat , MECH 241, UoB 28 Matrix Operations • The matrix multiplication operator calculates the product of two matrices with the formula: Mc. Sabat , MECH 241, UoB 29 Matrix Operations • The following table provides a summary of matrix arithmetic operators in MATLAB. For function-specific information, click the link to the function reference page in the last column. Operator Purpose Description Reference Page * Matrix multiplication C = A*B is the linear algebraic product of the matrices A and B. The number of columns of A must equal the number of rows of B. \ Matrix left division x = A\B is the solution to the equation Ax = B. mldivide Matrices A and B must have the same number of rows. / Matrix right division x = B/A is the solution to the equation xA = B. Matrices A and B must have the same number of columns. In terms of the left division operator, B/A = (A'\B')'. ^ Matrix power A^B is A to the power B, if B is a scalar. For other values mpower of B, the calculation involves eigenvalues and eigenvectors. ' Complex conjugate transpose A' is the linear algebraic transpose of A. For complex matrices, this is the complex conjugate transpose. mtimes mrdivide ctranspose ❖Example: MatrixOpExp.mlx Mc. Sabat , MECH 241, UoB 30 Matrix Operations • L = tril(A) returns the lower triangular portion of matrix A. • L = tril(A,k) returns the elements on and below the kth diagonal of A. • U = triu(A) returns the upper triangular portion of matrix A. • U = triu(A,k) returns the elements on and above the kth diagonal of A. ❖Example: MatrixOpExp.mlx Mc. Sabat , MECH 241, UoB 31 References • https://www.mathworks.com/help/matlab/line ar-algebra.html • https://www.mathworks.com/help/matlab/ • Introduction to MATLAB, Ossman K., Bucks G. 2014. • An Engineering Guide to MATLAB® with Applications from Mechanical, Aerospace, Electrical, Civil and Biological System Engineering, Magrab E., Azarm S., Balachandran B., Duncan J., Herold K., Walsh G., 3rd ed. Prentice Hall, 2011. Mc. Sabat , MECH 241, UoB 32