%% 034IN "Fundamentals of Automatic Control" - Introduction to MATLAB
%% Part 3 - Vectors & Matrices
%%
% This is the third MATLAB live script of the collection 034IN "Fundamentals of Automatic Control" - Introduction to MATLAB, devoted to introduce the MATLAB environment and tools for solving practical problems related to the topics of the 034IN course, i.e. performance analysis of dynamic systems, design of control law for continuous-time linear dynamical systems, approximate discretization of a continuous-time control law etc.
% Use this link to go back to the main live script of the collection.
% Table of Contents
% 034IN "Fundamentals of Automatic Control" - Introduction to MATLAB
% Part 3 - Vectors & Matrices
%      Objectives
%     Introduction
%     With a Little Help from the 'help' Command!
%     Row vectors
%         Elements of Vectors
%         Accessing Several Elements of a Vector
%         Number of Elements in a Vector
%         The Colon Operator
%         The linspace Command
%         Indexing Vectors
%         Vector Arithmetic
%             Addition of Two Vectors
%             A Vector Times a Scalar
%             Adding a Scalar to a Vector
%         Element by Element Operations
%     Column Vectors
%         Operations with Column Vectors
%     Add Row and Column Vectors
%     Transpose of a Vector
%     Creating a Matrix
%         Joining Matrices
%     Fast Ways to Create a Matrix
%         Size of a Matrix
%         Elements of a Matrix - Indexing
%             Rows/Columns of a Matrix
%             Several Elements
%             Sub-matrices
%         Matrix Arithmetic
%         Matrix Multiplication
%         Connections Between Vectors and Matrices
%         Matrix Powers
%         Element-wise Operations
%     Summary
%             Back to the Index
%             Back to the Previous Part: Numbers, Arithmetic Operations, Formats and Variables
%             Go to the Next Part: Symbolic Math Computations
%
%
%%  Objectives
%
%  The aim of this live script is
%  to understand how to create and manipulate vectors in MATLAB;
%  to understand how to create and manipulate matrices in MATLAB.
%%
%% Introduction
% One of the great powers of mathematics and MATLAB is the ability to work with both with vectors and matrices of virtually any size (2 by 2, 10 by 10, 100 by 100000). Matrices and vectors are essential tools in many applications, describing quantities like the concentrations of different chemicals at different points in time, the prices of  assets (stocks, companies, equipment, etc) at different points in time, and the temperature at different points in a body. Most often matrices are associated with a linear system which we want to solve, if possible.
%
%
%% With a Little Help from the 'help' Command!
% Here is a list of the main categories of topics, available with the help command, related to the manipulation of vectors and matrices

help ops

% Elementary matrices and matrix manipulation

help elmat

% Matrix functions - numerical linear algebra

help matfun

% Sparse matrices

help sparfun

%
%
%
%% Row vectors
%
% In MATLAB you can create a row vector using square brackets [ ]. Elements of the vector may be separated either by one or more blanks or a comma

xr1 = [1 -3 4]
xr2 = [1, -3, 4] 

%
%% Elements of Vectors
% To refer to elements in a vector MATLAB uses round brackets ( )

xr1(3) % the current value of the last element in xr1

xr1(3) = 0; % This assigns the value 0 to the last element of xr1.

%
%% Accessing Several Elements of a Vector
% The elements of a vector are indexed, starting with 1 and continuing to the length of the vector.
% MATLAB uses vectors of integers between 1 and the length of a vector to refer to several elements of a vector at once. For example

xr1([1 3]) % selecting the 1st and the 3rd element in xr1

IDlist = [1 3 2 3 1];
sampleV = xr2(IDlist) % This produces a vector consisting of the elements of xr2 
                      % corresponding to the values in IDlist and assigns the 
                      % result to a variable called sampleV. 

%
%% Number of Elements in a Vector
% The number of elements in an array (for instance a vector) can be found using the MATLAB command numel

numel(sampleV)

% The length of a vector can also be found using the MATLAB command length

length(sampleV)

%
%% The Colon Operator
% Frequently you want to create vectors whose elements are defined by a simple expression or to access a sequence of elements in a vector. The colon operator :  provides a very convenient way of doing this.
% In its simplest form
% x = a:b
% the first element in the vector x is the a
%  value, then the next element is a+1, and so on, until b is reached

x = -12:4

% A slightly more general form of the colon operator is
% y = a:step:b
% which starts at a, then adds step repeatedly, until b is reached (or exceeded). In fact the value of step does not have to be an integer. It can even be negative.

 y1 = 5:2:10
 y2 = 1 + 0.05*(0:10)
 y3 = 1:0.05:1.5 % y2 and y3 have the same values
 y4 = 2:-0.05:1.65

%
%% The linspace Command
% The task of creating a vector of equally (or linearly) spaced points between two limits occurs so commonly that MATLAB has a special command  to do this:
% linspace(a, b, n)
% The command creates n equally spaced values between a and b, including both a and b.

 z1 = linspace(1, 2, 8) % 7 intervals - why?
 z2 = linspace(1, 2, 9) % 8 intervals 

%
%% Indexing Vectors
% The colon operator is very helpful for indexing elements of a vector

 z2(1:5) % select the first 5 elements of the vector z2
 y2(3:2:11) % select the 3rd, 5th, 7th, 9th and 11th elements of the vector y2

%
% The MATLAB keyword end is used for several purposes. When referring to an element of a vector, it refers to the last element

 y4(end-3:end) % the last 4 element in y4

%
%% Vector Arithmetic
% The standard vector operations of adding two vectors and multiplying a vector by a scalar work in MATLAB.
%% Addition of Two Vectors
% The sum of two vectors of the same size is obtained by adding corresponding elements

 a = [1 2 3];
 b = [10 11 12];
 c = a+b
 d = a .* b

% Try adding vectors of different sizes

 a1 = 1:3;
 b1 = 10:15;
 %a1+b1

%% A Vector Times a Scalar
% Multiplying a vector by a scalar produces another vector of the same size in which each element of the original vector has been multiplied by the scalar

 b2 = 2.5 *b1

%% Adding a Scalar to a Vector
% A scalar may be added to any vector producing a new vector with the scalar added to each element of the vector

 b3 = b2+2.2

%
%% Element by Element Operations
% Sometimes it is very useful to apply arithmetic operations to each element of a vector (or even a matrix). These element by element operations are
%  .* to multiply corresponding elements of two vectors
%  ./ to divide corresponding elements of two vectors
%  .^ to take powers of each element of a vector
% Evaluate
% x_k = k^2\;,\quad k=1\,,\;2\,,\;\ldots 5

 iv = (1:5);
 xa = iv .* iv
 xb = iv .^2   % compare xa and xb

%     Many MATLAB functions, for example exp and sqrt, work with vectors, applying the function to each element of the vector.
%
%% Column Vectors
%
% In MATLAB you can also create a column vector using square brackets [ ]. However, elements of a column vector are separated either by a semicolon ;    or a newline

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

 xv2 = [-1
         2
         3
         0]
 % they have the same elements

%% Operations with Column Vectors
% Elements of a column vector are accessed using round brackets ( ), exactly the same as for row vectors.
%
%% Add Row and Column Vectors
%
% By adding a row vector x and a column vector y, you will obtain a matrix with each element (i,\,j) in the matrix equal to x(i)+y(j)

rv = [1 2 3];
cv = [4; 5; 6;7];
z = rv+cv

%
%% Transpose of a Vector
% You can convert a row vector into a column vector (and vice versa) using the transpose operator ' (an apostrophe) or the command transpose

x_c = [1 2 3 4]'

tt = x_c'

y_r = [4; 3; 2; 1]'

x_c1 = transpose([1 2 3 4])

y_c1 = transpose(y_r)

%
%% Creating a Matrix
%
% In MATLAB you can create a matrix using square brackets [ ]. Elements of a row are separated either by one or more blanks or a comma ,. Rows are separated by a semicolon ; or a newline.
% A matrix must have the same number of elements in each row and the same number of elements in each column, thus an m by n matrix is a array of m rows each of n elements or equivalently n columns each with m elements.

A = [ 1 2 3 4; 5 6 7 8; 0 9 8 7]

A(1, 2)
A(1:2, 2:4)

%
%% Joining Matrices
% You can join matrices together using square brackets [ ], provided the sizes match.

r1 = 1:3;
r2 = 4:6;
A = [r1; r2] % two row vectors, stacked on top of each other

%

c1 = [1; 4]
c2 = [2; 5]
c3 = [3 6]'
A = [c1 c2 c3] % The matrix A has three columns joined side by side.

%

A = [1 2 3; 4 5 6]
B = [10 11 12; 13 14 15]
C = [A B] % As A and B have the same number of rows they may be joined side by side. C is a 2 by 6 matrix.

D = [A; B] % As A and B have the same number of columns they may be stacked. D is a 4 by 3 matrix.

%
%% Fast Ways to Create a Matrix
% MATLAB provides efficient functions to create some commonly used matrices:
% The command zeros(m,n) creates an m by n array (matrix) of zeros.
% The command ones(m,n) creates an m by n array (matrix) of ones.
% The command eye(n,n) creates an n by n identity matrix.
% The command rand(m,n) creates an m by n matrix whose elements  are random numbers, uniformly distributed between 0 and 1.
% The command randn(m,n) creates an m by n matrix whose elements  are random numbers, Gaussian distributed with mean value 0 and variance 1.

A1 = zeros(5, 3)
A2 = ones(3, 5)
I4 = eye(4) % compact form, equivalent to eye(4,4)
R1 = rand(3,4)
G1 = randn(3,3)

%
%% Size of a Matrix
% The dimensions (number of rows, number of columns) of a matrix can be found using the MATLAB command size

[~,c]= size(I4)

size(R1)

%
%% Elements of a Matrix - Indexing
%
% In MATLAB A(i,j) accesses the element A_{i\,,\,j} in row i, column j of the matrix A

A = zeros(3); % compact form of zeros(3, 3)
A(1,3) = 3;
A(3,1) = -3;
A

%
%% Rows/Columns of a Matrix
% You can access a row or a column of a matrix using the colon : operator to refer to all of a row or all of a column

A = [1 2 3; 4 5 6; 7 8 9]
r2 = A(2, :)
c3 = A(:, 3)

%
%% Several Elements
% The colon : referring to the whole row or column, can be replaced by a vector of indices

u = A(1, [1 3])
v = A([1 2], 1)

%
%% Sub-matrices
% If you refer to more than one row and more than one column of a matrix, then you get a sub-matrix consisting of all the elements in those rows and columns

B1 = A(1:2, [1 3])
B2 = A(:, [1 3])

%
%% Matrix Arithmetic
% Addition and subtraction are defined for matrices of the same dimensions, and work element-wise.
% Multiplication of a matrix by a scalar is also defined element-wise, just as for vectors.

A = [1 2 3 0; 3 4 5 -1; 5 6 7 8]
B = -2*A
C = 2*A + B

%
%% Matrix Multiplication
% In MATLAB the multiplication operator * represents matrix multiplication.
% If  A and  B are not scalars, then A*B is only defined if the number of columns in  A    is equal to the number of rows in  B.

A = [1 2; 3 4; 5 6]
B = [5 6; 7 8]
C = A*B

% Remember: matrix multiplication is not commutative.
%
%% Connections Between Vectors and Matrices
%
% A row vector with n elements is equivalent to a 1 by n matrix.
% A column vector with m elements is equivalent to a m by 1 matrix.

A = [1 2 3 0; 3 4 5 -1; 5 6 7 8]
b = [1;2;3;4]
v = A*b

r = [3 2 1]
w = r*A

x = rand(3,1)
y = rand(3,1)
p = x'*y % the dot product of x and y

%
%% Matrix Powers
% Just as * represents matrix multiplication, ^ represents the multiplication of matrices together

A = [1 2; 3 4]
B = A^2
C = A^3

%
%% Element-wise Operations
% MATLAB provides the operators .* for element by element multiplication, ./ for element by element division and .^ for element by element powers. This works is the same way as with vectors.

A = [1 2 3; 4 5 6]
B = 1./A

%%
%
%% Summary
%
% Using this live script you have:
% learned how to use square brackets [ ]    to create row or column vectors;
% learned how to access elements of a vector and to find the number of elements in a vector;
% learned about fast ways to create vectors using the : operator;
% learned about indexing to refer to some elements of a vector;
% learned about vector arithmetic, both in the usual mathematical sense and element by element operations;
% learned about the transpose  operator ';
% learned how to use square brackets [ ]    to create matrices;
% learned about fast ways to create matrices using zeros, ones, rand and eye;
% learned about ways access elements, rows, columns or sub-matrices of a matrix;
% learned about matrix arithmetic;
% learned about elementary and specialized matrix functions.
%
%
%% Back to the Index
% Use this link to go back to the main live script of the collection.
%
%% Back to the Previous Part: Numbers, Arithmetic Operations, Formats and Variables
% Use this link to go back to the previous live script of this collection.
%
%% Go to the Next Part: Symbolic Math Computations
% Use this link to go to the next live script of the collection.
%
%
%