Exercise 3
Part 1. Solving a system Ax = b **Create a function in MATLAB thatbegins with: function [C,N]=solvesys(A) [~,n]=size(A);b=fix(10*rand(n,1)) format long We are using format long to displaya number in exponent format with 15 digit mantissas. If later on,you will need to switch back to the default format, type and runformat The input is an matrix A. If A is invertible, the outputsare the matrix C, whose 3 columns x1, x2, x3 are the solutionsobtained by the three methods described above, respectively, and Nis the vector whose 3 entries are the 2-norms of the vectors of thedifferences between each two solutions.
**First, check if A is invertible. If A is not invertible, thefunction returns an empty matrix C=[ ] and an empty vector N=[ ].Also, in this case, there are two possibilities for the system Ax =b: either “the system is inconsistent” or “the solution is notunique”. Use the command rank to check it on the two possible casesand program the two corresponding output messages. After that,terminate the program.
If A is invertible, the function solves the equation Ax = busing the three methods described above and gives the outputvectors x1, x2, x3 for each of the methods (1)-(3), respectively.The vectors have to be the columns of the matrix C. Thus, weassign: C=[x1, x2, x3 ];
**The function [C,N]=solvesys(A) also returns a column vectorN=[n1;n2;n3]; where n1=norm(x1-x2); n2=norm(x2-x3); n3=norm(x3-x1);The entries of the vector N are the 2-norms of the vectors of thedifferences between each two distinct solutions. Each entry iscalculated by using a built-in MATLAB function norm, which is asquare root of the sum of squares of the entries of the vector. Thevector N gives an idea how “different” are the solutions obtainedby various methods.
**Type the function solvesys in your Live Script.
**Run the function [C,N]=solvesys(A) for the following choicesof the matrix A:
(a) A = magic(6); (b) A = magic(7); (c) A = eye(4); % Write acomment on the output for part (c) by comparing the solution withthe vector b. (d) A = randi(20,4), (e) A = magic(3); (f) A =hilb(7)
Part 2. Condition numbers **Find the condition numbers of thematrices A=magic(7) and A=hilb(7) c1=cond(magic(7))c2=cond(hilb(7))
% Compare c1 and c2 with number 1 and explain in your dairy filewhy the norms of the differences between the solutions for thecoefficient matrix in part (f) are so big compared with the onesfor the matrix in part (b).
**Explore the sensitivity of a badly conditioned matrix hilb(7):Input: A=hilb(7); Run the following: b=ones(7,1); x=A; b1=b+0.01;y=A1; norm(x-y) c3=rcond(A) %Using the output c3, which is thereciprocal condition number, explain why the system with thecoefficient matrix hilb(7) is sensitive to perturbations.
**Re-run the code above for: A=magic(7);
%Comment on sensitivity to perturbations of magic(7) comparedwith hilb(7) by analyzing the corresponding outputs for thenorm(x-y) and c3.