MATLAB sessions: Laboratory MAT 75 Laboratory Matrix Computations and Programming in MATLAB In this laboratory session we will learn how to. Create and manipulate matrices and vectors.. Write simple programs in MATLAB Matrices and Linear Algebra Matrices can be constructed in MATLAB in different ways. For example the matrix can be entered as or >> A=[8,,6;,5,7;4,9,] >> A=[8,,6;,5,7; 4,9,] or defined as the concatenation of rows >> row=[8,,6]; row=[,5,7]; row=[4,9,]; A=[row;row;row] or columns >> col=[8;;4]; col=[;5;9]; col=[6;7;]; A=[col,col,col] Note the use of, and ;. Concatenated rows/columns must have the same length. Larger matrices can be created from smaller ones in the same way: >> C=[A,A] % Same as C=[A A] C =
MATLAB sessions: Laboratory The matrix C has dimension 6 ( by 6 ). On the other hand smaller matrices (submatrices) can be extracted from any given matrix: >> A(,) % coefficient of A in nd row, rd column 7 >> A(,:) % st row of A >> A(:,) % rd column of A 6 7 >> A([,],[,]) % keep coefficients in rows & and columns & 6 9 Some matrices are already predefined in MATLAB: >> I=eye() % the Identity matrix I = 0 0 0 0 0 0 >> magic() (what is magic about this matrix?) Matrices can be manipulated very easily in MATLAB (unlike Maple). Here are sample commands to exercise with: >> A=magic(); >> B=A % transpose of A, i.e, rows of B are columns of A B = 8 4 5 9 6 7 >> A+B % sum of A and B 6 4 0 4 0 6 0 6 4 >> A*B % standard linear algebra matrix multiplication 0 7 5 7 8 7 5 7 0 >> A.*B % coefficientwise multiplication 64 4 5 6 4 6 4
MATLAB sessions: Laboratory Try A*A, A^, A.^. The MATLAB command A is especially relevant when studying the solution of linear systems of differentials equations:. determines the solution x = A b of the linear system Ax = b. The array b must have as many rows as the matrix A.. [S,D]=eig(A) determines the eigenvectors of A (columns of S) and associated eigenvalues (diagonal coefficients of D) (note that the eig function has one input and two output arguments). As an example consider the matrix magic() again and x = : >> A=magic() >> x=[,,] % same as x=[;;] x = >> b=a*x b = 8 4 8 >> A\b % this is x! >> inv(a)*b % less efficient and accurate.0000.0000.0000 >> [S,D]=eig(A) S = -0.5774-0.8-0.46-0.5774 0.474-0.474-0.5774 0.46 0.8 D = 5.0000 0 0 0 4.8990 0 0 0-4.8990 >> A*S(:,)-D(,)*S(:,) % test st eigenvector-eigenvalue pair.0e-04 * -0.776 0.55-0.55
4 MATLAB sessions: Laboratory Note the multiplicative factor 0 4 in the last computation. MATLAB performs all operations using standard IEEE double precision. Important!: Because of the finite precision of computer arithmetic and roundoff error, vectors or matrices that are zero (theoretically) may appear in MATLAB in exponential form such as.0e-4 M where M is a vector or matrix with entries between and. This means that each component of the answer is less than 0 4 in absolute value, so the vector or matrix can be treated as zero (numerically) in comparison to vectors or matrices that are on the order of in size. MATLAB Programming Several constructs are used in MATLAB:. repetitive loops (fixed number of times) for <expression>. repetitive loops (indefinite number of times) while <expression>. conditional branching if expression elseif expression : else The following examples illustrate the use of each construct:. for loop: determine the sum of the squares of integers from to 0 S = 0; % initialize running sum for k = :0 S = S+k^; What is S? Verify with MATLAB.. while loop: determine the sum of the inverses of squares of integers from until the inverse of the integer square is less than 0 0 S = 0; % initialize running sum k = ; % initialize current integer incr = ; % initialize test value while incr>=e-0 S = S+incr; k = k+; incr = /k^;
MATLAB sessions: Laboratory 5 What is the value of S returned by this script? Compare to Can k and incr be both initialized by 0?. if statement: evaluate y = x function y=f(x) if x== disp( y is undefined at x = ) else y=/(x-); Try f(), f(). k= for a given (but unknown) scalar x k = π 6. Whenever possible all these construct should be avoided and built in MATLAB functions used instead to improve efficiency. In particular lengthy do loops introduce a substantial overhead. Compare >> n = 0^7; >> tic; S=0; for k=:n; S=S+/k^; ; toc; S Elapsed time is 0.04094 seconds. S =.6449 and >> tic; S=sum(./(:n).^); toc; S Elapsed time is 0.4895 seconds. S =.6449 Note that the Elapsed time, i.e. the computational time, is longer with the for loop than it is by using the built in MATLAB function sum. Note also that the Elapsed time varies deping on the machine you are using. Programming with MATLAB is fairly easy. Still a script or function may not execute properly due to some programming error. In this case MATLAB returns an error indicating where it stopped and why. Most of the time this is sufficient to find out the error and correct it, especially when you get used to it. But keep in mind that even non-fatal mistakes may eventually force a program to later crash. Exercises Instructions: For your lab write-up follow the instructions of LAB.. Enter the following matrices and vectors in MATLAB 4 7 5 8, B = 4 5 6, c = [ 4 ], d = 6 9 7 8 9 (a) Perform the following operations: AB, BA, cb and Ad [ B (b) Construct a 6 matrix C = [ A B ] and a 4 matrix D = c ]. (c) Replace A(, ) with 0. (d) Extract the rd row of the matrix A.
6 MATLAB sessions: Laboratory (e) A row or a column of a matrix can be deleted by assigning the empty vector [] to the row or the column. For instance A(,:)=[] deletes the second row of the matrix A. Delete the third row of the matrix B.. Recall that a geometric sum is a sum of the form a + ar + ar + ar +.... (a) Write a function file that accepts the values of r, a and n as arguments and uses a for loop to return the sum of the first n terms of the geometric series. Test your function for a =, r = / and n = 0. (b) Write a function file that accepts the values of r, a and n as arguments and uses the built in command sum to find the sum of the first n terms of the geometric series. Test your function for a =, r = / and n = 0. Hint: Start by defining the vector e=0:n- and then evaluate the vector R = r.^e. It should be easy to figure out how to find the sum from there.. Write a function file that creates the following piecewise function: x +, x f(x) = e x, < x 5 x x 0, x > 5 Assume x is a scalar. The function file should contain an if statement to distinguish between the different cases. The function should also display the function is undefined at x = 0 if the input is x = 0. Test your function by evaluating f(), f(4), f(7) and f(0). 4. Write a script file that creates a row vector v containing all the powers of below 000. The output vector should have the form: v = [, 4, 8, 6... ]. Use a while loop. 5. The counter in a for or while loop can be given explicit increment: for i =m:k:n to advance the counter i by k each time. In this problem we will evaluate the product of the first 0 odd numbers 5... 9 in two ways: (a) Write a script file that evaluates the product of the first 0 odd numbers using a for loop. (b) Evaluate the product of the first 0 odd numbers using a single MATLAB command. Use the MATLAB command prod. 6. Write a function file which takes as input an n vector x and an integer m, and returns as x x output the vector y =.. mx Test your file for x = and m =.