%This file was prepared by Amos Ron for the sake of his LinearAlgebra
%class demonstartion for cs412 during Spring99.

%we study in this demo various linear algebra topics
%if you copy and run this file, add for your convenience
%`pause' commands. otherwise, open a diary before you run the file

%the first topic: how to measure the size of an error?

v=[-6 7 .5 -1]

% we measure the magnitude of v in four different ways
norm(v,1)
norm(v,2)
norm(v,inf)
norm(v,'fro')

%Now, we compute matrix norms


A=[-1 2 0; 3 -1 2]

%we measure the magnitude of A in four ways, too 
norm(A,1)
norm(A,2)
norm(A,inf)
norm(A,'fro')


%Second topic: linear systems
%first, a warm-up: the simplest code for solving an equation
A=[1 1; 2 -1]
b=[7;8]
x=A\b


clear all


%now a real example

A=[17 24 1 8 15; 23 5 7 14 16; 4 6 13 20 22; 10 12 19 21 3;11 18 25 2 9]

cond(A)
%the condition number indicates that this matrix is `good'


%we now LU-factor A
[L, U, P]=lu(A);

L
U
PA=L*U
%L*U is a permuted version of A. P is the permutation matrix

P*A
%indeed, P*A and L*U seem to be the same. Let's see if their difference
%is really small
norm(PA-ans,2)
%it is small. the difference is due to minor round-of errors


%next, we solve an equation Ax=b using the LU factorization
%first, we convert the system in PA*x=P*b, since LU is a factorization of PA
b=[1 0 0 0 0]';
bp=P*b


y=L\bp
x=U\y

%we now compare that to the direct solution x=A\b. Note that A\b
%is not really a direct solution. In order to find A\b, matlab
%LU-factor again the matrix A. In fact, matlab will simply
%repeat exaclty all the work that we did above.

x1=A\b
norm(x-x1,2)



%Another factorization is the the QR factroization
[Q,R]=qr(A);
R

Q*R

norm(A-Q*R,2)
norm(A-Q*R,1)
norm(A-Q*R,'fro')

%R is upper triangular, but what kind of matrix is Q?
Q
Q*Q'
norm(eye(5)-ans,2)
%Q is an orthogonal matrix, i.e., a matrix whose transpose is its inverse





