clear
echo on
%This script demonstrates the norm of a
%matrix A and its relation to the condition
%number.  The condition number is used in
%determining the sensitivity of the solution
%of a system of equations to the errors in
%the matrix and the right hand side.
%
%First we set up the matrix a:
a=[1 2; 3 5.9]
pause
%We wish to determine the variation of the ratio
%||Ax|| / ||x|| to the -direction- of the vector
%x.  Note that this ratio is independent of the
%length of x, and is only a function of its direction
%and the way in which that direction interacts
%with the matrix A.  For a 2 dimensional vector we
%can describe this vector with the angle theta.  Thus:
pause
theta=[0:.01:2*pi];
npt=length(theta);
for i=1:npt
  x=[cos(theta(i)),sin(theta(i))]';
  %Here we use the transpose because we need a column
  %vector for x.
  
  b=a*x;
  
  %And finally, we calculate the ratio of the norms.  The
  %'1' in the norm command specifies the manhattan norm.
  m(i)=norm(b,1)/norm(x,1);
  echo off
end;
echo on
pause
%Let's plot the ratio vs. the direction of the vector x:
figure(1)
plot(theta,m)
set(gca,'FontSize',18)
xlabel('theta')
ylabel('norm(b)/norm(n)')
%Note that the ratio is a strong function of the angle.
%The maximum value is the norm of matrix A, which is equal
%to the maximum of the norms of all of the columns of A.
%For this matrix the maximum is 7.9.
pause
%The minimum is 1/||inv(A)||.  We can determine this as:
ainv=inv(a)
%so the minimum is just 1/89 = 0.0112.  This is close
%to the value we get off of the plot:

min(m)
pause

%The discrepancy occurs because we haven't picked a vector
%x which quite corresponds to the direction of the minimum.
%
%Finally, we turn to the condition number.  This is equal to
%||inv(A)||*||A||, or the max divided by the min of ||Ax|| / ||x||
%Thus we get:
condition=max(m)/min(m)
%We can compare this to the value estimated by the matlab
%function 'cond(A)':
cond(a)
pause
%As you can see, the two are a bit different.  This is because
%the matlab routine calculates the condition number using
%the 2-norm rather than the manhattan norm used in class.
%The 2-norm condition number is defined as the ratio of the largest 
%to the smallest of the singular values of the matrix.  We will
%get into singular value decomposition next week.  The manhattan
%norm condition number can be estimated from the command:
condest(a)
pause
%Note that this value isn't always correct either - it uses an
%algorithm to estimate the condition number because calculating
%it exactly takes many more computations than an LU decomposition!
echo off