Question: This exercise asks for a user-defined function to compute the trace of a square matrix. The trace of a square matrix A, denoted by tr(A),

This exercise asks for a user-defined function to compute the "trace" of a square matrix. The trace of a square matrix A, denoted by tr(A), is the sum of the elements on the main diagonal of A. That is, for an n x n square matrix 1011 ain 012 d22 a21 aan . A= .. ani ana . ann its trace is defined as n tr(A) = a Qui = 011 +222 + ... + ann (1) The trace is only defined for a square matrix. In other words, the compatibility condition for the trace of a matrix is that the number of rows and the number of columns of the matrix should be equal. To begin, download the template file Rec4Ex2.m and make sure that the "Current Folder" in Matlab is set to one containing the downloaded file. Open this file in the Matlab script Editor. Scroll down to the locate the comment & Enter the function definition after this comment. Note that the Matlab code to call and test your function has already been provided in the top half of the file Rec4Ex2.m. Please do not make any modifications to that script. You will implement a function named mytracefun that accepts a matrix variable A as input whose trace you need to compute. The function should return one output, namely, a scalar value tr_val. The function should check whether A is a square matrix. The variable tr_val should be set to the trace of A if A is square. If A is not a square matrix, then tr_val should be assigned the value NaN. (NaN is a special value in Matlab, which stands for "Not a Number"). You may find the following built-in functions useful to complete your function definition: size, diag, and sum. Note that Matlab provides a built-in function trace to compute the trace. In this exercise, do not use the built-in trace command in your function definition. Instead, you are required to write code to compute the trace per equation (1) yourself. 5 Code for calling the user-defined function. ****** DO NOT MODIFY ******* 6 7 8- 9 10 12 37 11 11 4; 45 38 15 59 41; 31 52 54 43 3; 29 49 2 31 5; 55 35 30 29 32); 11 12 13 14 15 - 16 - 17 - tr A mytracefun (A); if (isnan(tr_A) disp("Matrix is not square") else disp(tr_A) end 18- 19- - B- 21 22 [-25 14 1 18 20 -20; 19 -21 29 -3 -25 -7; 19 10 9 -4 -22 20); 23 24 25 26 27 28- 29 30 - 31 tr B mytracefun (B); if (isnan (tr_B)) disp("Matrix is not square") else disp (tr_B) end I 32 - 33 C - eye (7); 34 35 36 37 38 39 40 trC mytracefun (C); if (isnan(trC)) disp ("Matrix is not square") else disp(tr_c) end Enter the function definition after this comment
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
