Question: %% Lab 2 - Your Name - MAT 275 Lab %% Example code % Example 1 % NOTE: Delete examples before submission. A = [1

%% Lab 2 - Your Name - MAT 275 Lab %% Example code % Example 1 % NOTE: Delete examples before submission. A = [1 0; 0 -1] A = [1, 0; 0, -1] % NOTE: The two matrices above are the same. We can separate columns with % commas OR spaces, and separate rows with semi-colons. %% % The following code changes the element in the 1st row and 2nd column of % matrix A to 9. In general, we can extract or change elements in a matrix A % with the syntax A(row,column). A(1,2) = 9 %% % We can create the original matrix A above one element at a time as % follows: % Initiate A as empty vector (optional but necessary in other cases). A = ; % Define A(1,1) = A(1,2) = A(2,1) = A(2,2) = matrix A one element at a time. 1; 0; 0; -1; % Display vector A. A %% % % % % This example shows how we can extract elements, rows, or columns from a matrix. A colon indicates "all elements." So A(2,:) extracts elements in all columns of A that are also in the 2nd row of A. Note: To run this section, a matrix A must be saved in the workspace. disp('Extract second row') % disp command displays a specified string A(2,:) disp('Extract first column') A(:,1) disp('Extract last element') A(end,end) %% % Let's declare a vector b and sove Ax = b where A is a known matrix, b is % a known vector, and x is an unkown vector with same dimensions as b. This % is the most fundamental problem in linear algebra. b = [1;2]; x = A\\b % solve Ax = b using backslash command % NOTE: These examples are not comprehensive. Make sure you also go through % the protocol examples. %% Exercise 1 % Part (a) %% % Part (b) %% % Part (c) % NOTE: Use the "backslash" command. NOT the division operator "/". %% % Part (d) %% % Part (e) %% % Part (f) %% Exercise 2 % Part (a) % % % % NOTE: We must create separate function M-files here. The require input variables. Therefore, you cannot use "run" function. You must invoke it by providing values for the Suppose we name our function geom_sum. Then complete the % % % % % % NOTE: You MUST comment each line of code in you M-file similar to how I comment each line of code in this script file. You may choose your own style of documentation, but make sure it is consistent throughout the semester and thoroughly explains what the code is doing. Further, you should have a comment at the beginning of each function file explaining what the function does. I WILL MARK OFF POINTS otherwise. % Display contents of geom_sum M-file. type 'geom_sum.m' % Assign values to input variables. r = ??; a = ??; function will to execute the input variables. following. n = ??; % NOTE: Do NOT define r,a, or n inside the function file. This defeats the % purpose of requiring input arguments. % Compute geometric sum for specified values of r,a, and n. geom_sum(??) %% % Part (b) % % % % % % NOTE: MATLAB has several built in functions. Here, we want to use the built-in function "sum" to compute the same geometric sum as computed in part (a). If x is a vector, then "sum(x)" sums all the elements of x. Therefore, the "sum" function takes a vector as input and sums its elements. Hence, we must create a vector containing all the terms of the sum we wish to compute and pass that vector as input to the sum function. %% Example for 2b x = [1, 1, 1]; sum(x) % NOTE: Answer should be 1 + 1 + 1 = 3. Type "help sum" in command window % for more info. %% Exercise 3 % Part (a) % % % % NOTE: When the protocol says to write a script file, you do not need to create a separate M-file. This main file is a script file and you can simply write the list of commands here. Please refer to the second example on page 5 before attempting this problem. % Initiate product P. P = ??; % Define starting iteration index. m = ??; % Define stepsize of iteration. k = ??; % Define ending iteration index. n = ??; % Compute product. for i = m:k:n % muliply P by next element at each iteration (suppress output) end % Display product. % NOTE: i = m:k:n is also a vector! A for-loop essentially iterates through % each element of a vector. Keep this in mind for part (b). % NOTE: Type "help for" in the command window for more info. %% % Part (b) % % % % % % % % % % NOTE: Emphasis on the part where it says "SINGLE COMMAND." That means ONE line of code. The "prod" function is another built-in function that, similar to "sum", takes in a vector as input, yet computes the product of all the elements of the input vector. So, we need to create a vector containing all the numbers between 1 and 15 with a stepsize of 2. Which vector declaration method is best when we know the stepsize? Also, in order to compute the product in a single command, we must declare the vector INSIDE the prod command as an input argument, as opposed to x = vector, prod(x). Instead, we do prod(vector). Type "help prod" in the command window for more info. %% Exercise 4 % % % % NOTE: When the protocol says to write a script file, you do not need to create a separate M-file. This main file is a script file and you can simply write the list of commands here. Refer to second example on page 6 of protocol before attempting this exercise. % Initiate variables. power = ??; k = ??; % initiate counter % Initiate vector V of powers of 3. V = ??; % Compute powers of 3 and store in V. while ?? < ?? % specify condition of while-loop: stop iterating once % condition is no longer satisfied power = ??; % compute next value of power at each iteration V = ??; % concatenate vector V with new element at each iteration k = ??; % increment counter k end % Display vector V. %% Exercise 5 % % % % % NOTE: Here, we must create a separate function M-file f that accepts one input argument, a value of the variable x. You may want to start creating a new folder for each lab as we will be using f multiple times to define different functions. Please refer to the example on the last page of the protocol before attempting this problem. % Display contents of function f M-file. type 'f.m' % Evaluate f at x = 1. f(??) % Evaluate % Evaluate % Evaluate % Evaluate % Evaluate f at x = 2. f at x = 3. f at x = 4. f at x = 7. f at x = 10. %% Lab 2 - Your Name - MAT 275 Lab %% Example code % Example 1 % NOTE: Delete examples before submission. A = [1 0; 0 -1] A = [1, 0; 0, -1] % NOTE: The two matrices above are the same. We can separate columns with % commas OR spaces, and separate rows with semi-colons. %% % The following code changes the element in the 1st row and 2nd column of % matrix A to 9. In general, we can extract or change elements in a matrix A % with the syntax A(row,column). A(1,2) = 9 %% % We can create the original matrix A above one element at a time as % follows: % Initiate A as empty vector (optional but necessary in other cases). A = ; % Define A(1,1) = A(1,2) = A(2,1) = A(2,2) = matrix A one element at a time. 1; 0; 0; -1; % Display vector A. A %% % % % % This example shows how we can extract elements, rows, or columns from a matrix. A colon indicates "all elements." So A(2,:) extracts elements in all columns of A that are also in the 2nd row of A. Note: To run this section, a matrix A must be saved in the workspace. disp('Extract second row') % disp command displays a specified string A(2,:) disp('Extract first column') A(:,1) disp('Extract last element') A(end,end) %% % Let's declare a vector b and sove Ax = b where A is a known matrix, b is % a known vector, and x is an unkown vector with same dimensions as b. This % is the most fundamental problem in linear algebra. b = [1;2]; x = A\\b % solve Ax = b using backslash command % NOTE: These examples are not comprehensive. Make sure you also go through % the protocol examples. %% Exercise 1 % Part (a) %% % Part (b) %% % Part (c) % NOTE: Use the "backslash" command. NOT the division operator "/". %% % Part (d) %% % Part (e) %% % Part (f) %% Exercise 2 % Part (a) % % % % NOTE: We must create separate function M-files here. The require input variables. Therefore, you cannot use "run" function. You must invoke it by providing values for the Suppose we name our function geom_sum. Then complete the function will to execute the input variables. following. % % % % % % NOTE: You MUST comment each line of code in you M-file similar to how I comment each line of code in this script file. You may choose your own style of documentation, but make sure it is consistent throughout the semester and thoroughly explains what the code is doing. Further, you should have a comment at the beginning of each function file explaining what the function does. I WILL MARK OFF POINTS otherwise. % Display contents of geom_sum M-file. type 'geom_sum.m' % r a n Assign values to input variables. = ??; = ??; = ??; % NOTE: Do NOT define r,a, or n inside the function file. This defeats the % purpose of requiring input arguments. % Compute geometric sum for specified values of r,a, and n. geom_sum(??) %% % Part (b) % % % % % % NOTE: MATLAB has several built in functions. Here, we want to use the built-in function "sum" to compute the same geometric sum as computed in part (a). If x is a vector, then "sum(x)" sums all the elements of x. Therefore, the "sum" function takes a vector as input and sums its elements. Hence, we must create a vector containing all the terms of the sum we wish to compute and pass that vector as input to the sum function. %% Example for 2b x = [1, 1, 1]; sum(x) % NOTE: Answer should be 1 + 1 + 1 = 3. Type "help sum" in command window % for more info. %% Exercise 3 % Part (a) % % % % NOTE: When the protocol says to write a script file, you do not need to create a separate M-file. This main file is a script file and you can simply write the list of commands here. Please refer to the second example on page 5 before attempting this problem. % Initiate product P. P = ??; % Define starting iteration index. m = ??; % Define stepsize of iteration. k = ??; % Define ending iteration index. n = ??; % Compute product. for i = m:k:n % muliply P by next element at each iteration (suppress output) end % Display product. % NOTE: i = m:k:n is also a vector! A for-loop essentially iterates through % each element of a vector. Keep this in mind for part (b). % NOTE: Type "help for" in the command window for more info. %% % Part (b) % % % % % % % % % % NOTE: Emphasis on the part where it says "SINGLE COMMAND." That means ONE line of code. The "prod" function is another built-in function that, similar to "sum", takes in a vector as input, yet computes the product of all the elements of the input vector. So, we need to create a vector containing all the numbers between 1 and 15 with a stepsize of 2. Which vector declaration method is best when we know the stepsize? Also, in order to compute the product in a single command, we must declare the vector INSIDE the prod command as an input argument, as opposed to x = vector, prod(x). Instead, we do prod(vector). Type "help prod" in the command window for more info. %% Exercise 4 % % % % NOTE: When the protocol says to write a script file, you do not need to create a separate M-file. This main file is a script file and you can simply write the list of commands here. Refer to second example on page 6 of protocol before attempting this exercise. % Initiate variables. power = ??; k = ??; % initiate counter % Initiate vector V of powers of 3. V = ??; % Compute powers of 3 and store in V. while ?? < ?? % specify condition of while-loop: stop iterating once % condition is no longer satisfied power = ??; % compute next value of power at each iteration V = ??; % concatenate vector V with new element at each iteration k = ??; % increment counter k end % Display vector V. %% Exercise 5 % % % % % NOTE: Here, we must create a separate function M-file f that accepts one input argument, a value of the variable x. You may want to start creating a new folder for each lab as we will be using f multiple times to define different functions. Please refer to the example on the last page of the protocol before attempting this problem. % Display contents of function f M-file. type 'f.m' % Evaluate f(??) % Evaluate % Evaluate % Evaluate % Evaluate % Evaluate f at x = 1. f at x = 2. f at x = 3. f at x = 4. f at x = 7. f at x = 10. MATLAB sessions: Laboratory 2 MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB In this laboratory session we will learn how to 1. Create and manipulate matrices and vectors. 2. Write simple programs in MATLAB NOTE: For your lab write-up, follow the instructions of LAB1. Matrices and Linear Algebra F Matrices 8 1 A = 3 5 4 9 can be constructed in MATLAB in different ways. For example the 3 3 matrix 6 7 can be entered as 2 >> A=[8,1,6;3,5,7;4,9,2] A = 8 1 6 3 5 7 4 9 2 or >> A=[8,1,6; 3,5,7; 4,9,2] A = 8 1 3 5 4 9 6 7 2 or defined as the concatenation of 3 rows >> row1=[8,1,6]; row2=[3,5,7]; row3=[4,9,2]; A=[row1;row2;row3] A = 8 1 6 3 5 7 4 9 2 or 3 columns >> col1=[8;3;4]; col2=[1;5;9]; col3=[6;7;2]; A=[col1,col2,col3] A = 8 1 6 3 5 7 4 9 2 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 2016 Stefania Tracogna, SoMSS, ASU 1 MATLAB sessions: Laboratory 2 >> C=[A,A] C = 8 1 3 5 4 9 % Same as C=[A A] 6 7 2 8 3 4 1 5 9 6 7 2 The matrix C has dimension 3 6 (\"3 by 6\"). On the other hand smaller matrices (submatrices) can be extracted from any given matrix: >> A(2,3) % coefficient of A in 2nd row, 3rd column ans = 7 >> A(1,:) % 1st row of A ans = 8 1 6 >> A(:,3) % 3rd column of A ans = 6 7 2 >> A([1,3],[2,3]) % keep coefficients in rows 1 & 3 and columns 2 & 3 ans = 1 6 9 2 F Some matrices are already predefined in MATLAB: >> I=eye(3) I = 1 0 0 1 0 0 >> magic(3) ans = 8 1 3 5 4 9 % the Identity matrix 0 0 1 6 7 2 (what is magic about this matrix?) F Matrices can be manipulated very easily in MATLAB (unlike Maple). Here are sample commands to exercise with: >> A=magic(3); >> B=A' % transpose of A, i.e, rows of B are columns of A B = 8 3 4 1 5 9 6 7 2 >> A+B % sum of A and B ans = 16 4 10 4 10 16 10 16 4 >> A*B % standard linear algebra matrix multiplication ans = 101 71 53 c 2016 Stefania Tracogna, SoMSS, ASU 2 MATLAB sessions: Laboratory 2 71 53 >> A.*B ans = 64 3 24 83 71 71 101 % coefficient-wise multiplication 3 25 63 24 63 4 F One MATLAB command is especially relevant when studying the solution of linear systems of differentials equations: x=A\\b determines the solution x = A1 b of the linear system Ax = b. Here is an example: >> A=magic(3); >> z=[1,2,3]' % same as z=[1;2;3] z = 1 2 3 >> b=A*z b = 28 34 28 >> x = A\\b % solve the system Ax = b. Compare with the exact solution, z, defined above. x = 1 2 3 >> y =inv(A)*b % solve the system using the inverse: less efficient and accurate ans = 1.0000 2.0000 3.0000 Now let's check for accuracy by evaluating the difference z x and z y. In exact arithmetic they should both be zero since x, y and z all represent the solution to the system. >> z - x % error for backslash command ans = 0 0 0 >> z - y % error for inverse ans = 1.0e-015 * -0.4441 0 -0.8882 Note the multiplicative factor 1015 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 1.0e-15 M where M is a vector or matrix with entries between 1 and 1. This means that each component of the c 2016 Stefania Tracogna, SoMSS, ASU 3 MATLAB sessions: Laboratory 2 answer is less than 1015 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 1 in size. EXERCISE 1 Enter the following matrices and vectors in MATLAB 5 1 3 12 0 7 16 A = 2 4 7 , B = 3 2 5 , b = 36 , 6 1 8 1 9 10 17 c= \u0002 1 2 3 \u0003 , 4 d= 3 2 (a) Perform the following operations: AB, BA, cA and Bd (use standard linear algebra multiplication). \u0014 \u0015 A (b) Construct a 6 3 matrix C = and a 3 4 matrix D = [B d]. B (c) Use the \"backslash\" command to solve the system Ax = b. (d) Replace A(3, 2) with 0. (e) Extract the 2nd row of the matrix A and store it in the vector a. (f) 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(2,:)= deletes the second row of the matrix A. Delete the third column of the matrix B. MATLAB Programming It is often advantageous to be able to execute a segment of a code a number of times. A segment of a code that is executed repeatedly is called a loop. To understand how loops work, it is important to recognize the difference between an algebraic equality and a MATLAB assignment. Consider the following commands: >> counter = 2 counter = 2 >> counter = counter +1 counter = 3 The last statement does not say that counter is one more than itself. When MATLAB encounters the second statement, it looks up the present value of counter (2), evaluates the expression counter + 1 (3), and stores the result of the computation in the variable on the left, here counter. The effect of the statement is to increment the variable counter by 1, from 3 to 4. Similarly, consider the commands: >> v=[1,2,3] v = 1 2 >> v=[v,4] v = 1 2 3 3 4 When MATLAB encounters the second statement, it looks up the present value of v, adds the number 4 as entry of the vector, and stores the result in the variable on the left, here v. The effect of the statement is to augment the vector v with the entry 4. There are two types of loops in MATLAB: for loops and while loops c 2016 Stefania Tracogna, SoMSS, ASU 4 MATLAB sessions: Laboratory 2 for loops When we know exactly how many times to execute the loop, the for loop is often a good implementation choice. One form of the command is as follows: for k=kmin:kmax end The loop index or loop variable is k, and k takes on integer values from the loop's initial value, kmin, through its terminal value, kmax. For each value of k, MATLAB executes the body of the loop, which is the list of commands. Here are a few examples: Determine the sum of the squares of integers from 1 to 10: 12 + 22 + 32 + . . . + 102 . S = 0; % initialize running sum for k = 1:10 S = S+k^2; end S Because we are not printing intermediate values of S, we display the final value of S after the loop by typing S on a line by itself. Try removing the \";\" inside the loop to see how S is incremented every time we go through the loop. Determine the product of the integers from 1 to 10: 1 2 3 . . . 10. p = 1; % initialize running product for k = 2:10 p = p*k; end p F Whenever possible all these construct should be avoided and built in MATLAB functions used instead to improve efficiency. In particular lengthy loops introduce a substantial overhead. The value of S in the example above can be evaluated with a single MATLAB statement: >> S = sum((1:10).^2) Type help sum to see how the built in sum function works. Similarly the product p can be evaluated using >> p = prod(1:10) Type help prod to see how the built in prod function works. EXERCISE 2 Recall that a geometric sum is a sum of the form a + ar + ar2 + ar3 + . . .. (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 = 5, r = 1/3 and n = 8. (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 = 5, r = 1/3 and n = 8. Hint: Start by defining the vector e=0:n-1 and then evaluate the vector R = r.^e. It should be easy to figure out how to find the sum from there. c 2016 Stefania Tracogna, SoMSS, ASU 5 MATLAB sessions: Laboratory 2 EXERCISE 3 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 8 odd numbers 1 3 5 . . . 15 in two ways: (a) Write a script file that evaluates the product of the first 8 odd numbers using a for loop. (b) Evaluate the product of the first 8 odd numbers using a single MATLAB command. Use the MATLAB command prod. while loop The while loop repeats a sequence of commands as long as some condition is met. The basic structure of a while loop is the following: while end Here are some examples: Determine the sum of the inverses of squares of integers from 1 until the inverse of the integer square is less than 1010 : 112 + 212 + . . . + k12 while k12 1010 . S = 0; % initialize running sum k = 1; % initialize current integer incr = 1; % initialize test value while incr>=1e-10 S = S+incr; k = k+1; incr = 1/k^2; end What is the value of S returned by this script? Compare to X 1 2 = . k2 6 k=1 Create a row vector y that contains all the factorials below 2000: y = [ 1!, 2!, 3!, . . . k! ] while k! < 2000. y = ; % initialize the vector y to the empty vector k = 1; % initialize the counter value = 1; % initialize the test value to be added to the vector y while value < 2000 y = [y, value]; % augment the vector y k = k+1; % update the counter value = factorial(k); % evaluate the next test value end y EXERCISE 4 Write a script file that creates a row vector v containing all the powers of 3 below 3000. The output vector should have the form: v = [ 3, 9, 27, 81 . . . ]. Use a while loop. c 2016 Stefania Tracogna, SoMSS, ASU 6 MATLAB sessions: Laboratory 2 if statement The basic structure of an if statement is the following: if condition elseif condition : else end Here is an example: Evaluate 3 x + 2, y= 1 , x2 x1 x>1 for a given (but unknown) scalar x and, if x = 2, display \"y is undefined at x = 2\". function y=f(x) if x==2 disp('y is undefined at x = 2') elseif x <= 1 y=x^3+2; else y=1/(x-2); end end We can test the file by evaluating it at different values of x. Below we evaluate the function at x = 1, x = 2 and x = 4. >> f(-1) ans = 1 >> f(2) y is undefined at x = 2 >> f(4) ans = 0.5000 EXERCISE 5 Write a function file that creates the following piecewise function: x1 e , x2 2 24 x7 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 = 7\" if the input is x = 7. Test your function by evaluating f (1), f (2), f (3), f (4), f (7) and f (10). c 2016 Stefania Tracogna, SoMSS, ASU 7

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Mathematics Questions!