The sum of all the diagonal entries of a square matrix A is called the trace of
ID: 3836263 • Letter: T
Question
The sum of all the diagonal entries of a square matrix A is called the trace of A. For instance, the trace of the matrix: A = [4 0 -2 5 7 -1 2 -1 2] is 13. Write a MATLAB function (or script) to read the size and the entries of a matrix A form an input file and to calculate its trace. The following is an example of a possible input file specifying the size and entries of a matrix a: Assume that the file has n + 1 lines. The first entry in the file is the size of the matriz n. Your program should read this number first and then use this number to read the entire matrix. Use "in_data.txt" as the name of the input file. Your code should use fopen, fscanf, fgetl, and for ... end statements. fid=fopen('filename', 'rt'); string=fgetl(fid); [array, number_if_entries_read] = fscanf (fid, '%g', number_of_entries_to_be_read); fprintf(' Comment or message ' %d %g ...' ', variable1, variable2, ...);Explanation / Answer
fid = fopen("Newfile.m","rt");
n = str2num(fgetl(fid)); %read size of matrix
mat = fscanf(fid,"%d",[n n]) %read matrix from file of size [n n]
sum = 0; %sum will calculate trace
for i = 1:n
sum = sum + mat(i,i);
end
printf("Trace = %d ", sum);
I hope this piece of code helps you. If incase you need more help on this, please let m know. I shall try my best to resolve all your issues.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.