echo on
%%%%% ch02_exa.m %%%%%
% Run script and study the effects of each line.

echo off
format compact;
format short;
disp(sprintf('**** Examples from Chapter 02 ****'));
disp(sprintf('**** Example 2.3 Vector norms *'));
echo on

V=[-1.6 1.2]';	% Vector norms:
%norm(V,p)	%Returns sum(abs(Vi).^p)^(1/p), for i=1..n and any p.
norm(V,1)	%Sum of absolute values of elements of vector V.
norm(V,2)	%Also norm(V). 
norm(V,inf)	%Returns max(abs(Vi)).

echo off
disp(sprintf('**** Example 2.4 Matrix norms *'));
echo on

A=[2 -1 1; 1 0 1; 3 -1 4];	% Matrix norms:
norm(A,1)	%The 1-norm is largest absolute column sum of A.
norm(A,2)	%The largest singular value of A (same as norm(A)).
svd(A)		%Singular values of A
norm(A,inf)	%The infinity norm is largest absolute row sum of A.


echo off
disp(sprintf('**** Example 2.5 Matrix condition number *'));
echo on

A=[.5 1.5 -.5;-.5 2.5 -.5; -.5 -.5 .5];	% Condition number is the ratio of 
			%maximum stretching to maximum shrinking that A produces on a vector.
			%The condition number of a matrix is defined as norm(A)*norm(inv(A)),
norm(A,1)*norm(inv(A),1)	% using norm 1 
norm(A,inf)*norm(inv(A),inf)	% using norm inf 
norm(A,2)*norm(inv(A),2)	% using norm 2 (default in MatLab)
cond(A)				% MatLab condition number of matrix A


disp(sprintf('**** Example 2.8 Small residual *'));
echo on
%%%% Suppose two approximate solutions for the following system
A=[0.913 0.659; 0.457 0.330]; 
b=[0.254 0.127]';
x1=[-0.0827 0.5]';	% first approximate solution
r1=b-A*x1		% residual
norm(r1,1)		% norm of residual r1

x2=[0.999 -1.001]';	% second approximate solution 
r2=b-A*x2		% residual
norm(r2,1)		% norm of residual r2

x=A\b			% The MatLab solution      
			% Even r2 is greater than r1 the approximated solution x2 is better.
log10(cond(A))		% log_10(cond(A)) digits were lost in the accuracy of the solution 
			% (the problem is ill-conditioned for our example).

