% IAP 2006 Introduction to MATLAB
% Linear Algebra and Calculus

% EXAMPLE 1 Linear Algebra 

% A. Solving a System of Linear Equations
% The coordinates (x1,y1), (x2,y2), (x3,y3) and (x4,y4) of four points are given.
% Find a cubic equation that passes through the four points:
% Y = c1*X^3 + c2*X^2 + c3*X + c4
% We need to solve the equation for the coefficients c1, c2, c3, and c4

% A1. Define Vectors X and Y
% X and Y are two column vectors: X = [x1; x2; x3; x4] and Y = [y1; y2; y3; y4]
% You may choose to use any coordinates. For example:
X = [1 5 8 10]; X=X'
Y = [54; 82; 40; 10]
% Plot the points to see them
plot(X, Y, 'ro')

% A2. Define Matrix A 
% If C = (c1 c2 c3) is the vector we want to solve for, 
% we need to define a matrix from the vector X, so that Y = AC
% There are several ways to create A. For example:

% Method 1:
A = [X(1)^3     X(1)^2     X(1)    1
     X(2)^3     X(2)^2     X(2)    1
     X(3)^3     X(3)^2     X(3)    1
     X(4)^3     X(4)^2     X(4)    1] 

% Method 2:
A = [X.^3   X.^2   X.^1    X.^0]

% Method 3:
A = [X.^3   X.^2   X   ones(4,1)]

% A3. Solve Y = AC for C
% There are three ways to compute C:

% Method 1 (not recommended) Using the inverse matrix of A, i.e. c = A^(-1)*Y
Ainv = A^(-1)
C = Ainv * Y

% Method 2 (recommended) Using Gaussian Elimination 
% This method applies the \ operator
C = A \ Y

% Method 3 Using row reduction of [A|Y]
% This method applies the built-in function rref
% Create a new matrix called AY
AY = [A Y]
R = rref(AY)
C = R(:,5)

% A4. Plot the cubic equation
x = [0 : 0.1 : 10];
y = polyval(C, x);
plot (x, y, 'r-')
hold on
plot (X, Y, 'bo')
hold off

% B. Finding Eigenvalues and Eigenvectors
% An eigenvalue and eingenvector of a square matrix A are a scalar lambda
% and a nonzero vector V such that A*lambda = A*V.

% B1. Create a square matrix; for example let us use the matrix A:
A
 
% B2. Compute the eigenvalues and eigenvectors of A
% Compute a column vector that contains the eigenvalues of A
lambda = eig(A)
% With two output parameters, e.g. S and Lambda, eig computes the eigenvectors 
% in the columns of S and stores the eigenvalues along the diagonal of
% the matrix Lambda
[S, Lambda] = eig(A)
% Lambda can also be created using the diag function:
Lambda = diag(lambda)

% Check solution
Sinv = S^(-1)
B = S*Lambda*Sinv
% B should be the same as A
A



