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.
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
Operators and special characters.
Arithmetic operators.
plus - Plus +
uplus - Unary plus +
minus - Minus -
uminus - Unary minus -
mtimes - Matrix multiply *
times - Array multiply .*
power - Array power .^
mldivide - Backslash or left matrix divide \
mrdivide - Slash or right matrix divide /
ldivide - Left array divide .\
rdivide - Right array divide ./
idivide - Integer division with rounding option.
kron - Kronecker tensor product
pagemtimes - Page-wise matrix multiply
pagetranspose - Page-wise transpose
pagectranspose - Page-wise complex conjugate transpose
pagemldivide - Page-wise left matrix divide
pagemrdivide - Page-wise right matrix divide
tensorprod - Tensor products between two tensors
Relational operators.
eq - Equal ==
ne - Not equal ~=
lt - Less than <
gt - Greater than >
le - Less than or equal <=
ge - Greater than or equal >=
Logical operators.
and - Element-wise logical AND &
or - Element-wise logical OR |
not - Logical NOT ~
punct - Ignore function argument or output ~
xor - Logical EXCLUSIVE OR
any - True if any element of vector is nonzero
all - True if all elements of vector are nonzero
Special characters.
colon - Colon :
paren - Parentheses and subscripting ( )
paren - Brackets [ ]
paren - Braces and subscripting { }
punct - Function handle creation @
punct - Decimal point .
punct - Structure field access .
punct - Parent directory ..
punct - Continuation ...
punct - Separator ,
punct - Semicolon ;
punct - Comment %
punct - Invoke operating system command !
punct - Assignment =
punct - Quote '
punct - Double quote "
transpose - Transpose .'
ctranspose - Complex conjugate transpose '
horzcat - Horizontal concatenation [,]
vertcat - Vertical concatenation [;]
subsasgn - Subscripted assignment ( ),{ },.
subsref - Subscripted reference ( ),{ },.
numArgumentsFromSubscript - Number of arguments for indexing methods
subsindex - Subscript index
metaclass - Metaclass for MATLAB class ?
Bitwise operators.
bitand - Bit-wise AND.
bitcmp - Complement bits.
bitor - Bit-wise OR.
bitxor - Bit-wise XOR.
bitset - Set bit.
bitget - Get bit.
bitshift - Bit-wise shift.
Set operators.
union - Set union.
unique - Set unique.
intersect - Set intersection.
setdiff - Set difference.
setxor - Set exclusive-or.
ismember - True for set member.
See also function_handle.
Elementary matrices and matrix manipulation
help elmat
Elementary matrices and matrix manipulation.
Elementary matrices.
zeros - Zeros array.
ones - Ones array.
eye - Identity matrix.
repmat - Replicate and tile array.
repelem - Replicate elements of an array.
combinations- Generate all element combinations of arrays.
linspace - Linearly spaced vector.
logspace - Logarithmically spaced vector.
freqspace - Frequency spacing for frequency response.
meshgrid - X and Y arrays for 3-D plots.
accumarray - Construct an array with accumulation.
: - Regularly spaced vector and index into matrix.
Basic array information.
size - Size of array.
length - Length of vector.
ndims - Number of dimensions.
numel - Number of elements.
disp - Display matrix or text.
isempty - True for empty array.
isequal - True if arrays are numerically equal.
isequaln - True if arrays are numerically equal, treating NaNs as equal.
height - Number of rows.
width - Number of columns.
Matrix manipulation.
cat - Concatenate arrays.
reshape - Reshape array by rearranging existing elements.
resize - Resize data by adding or removing elements.
paddata - Pad data.
trimdata - Trim data.
diag - Diagonal matrices and diagonals of matrix.
blkdiag - Block diagonal concatenation.
tril - Extract lower triangular part.
triu - Extract upper triangular part.
fliplr - Flip matrix in left/right direction.
flipud - Flip matrix in up/down direction.
flip - Flip the order of elements.
rot90 - Rotate matrix 90 degrees.
: - Regularly spaced vector and index into matrix.
find - Find indices of nonzero elements.
end - Last index.
sub2ind - Linear index from multiple subscripts.
ind2sub - Multiple subscripts from linear index.
bsxfun - Binary singleton expansion function.
Multi-dimensional array functions.
ndgrid - Generate arrays for N-D functions and interpolation.
permute - Permute array dimensions.
ipermute - Inverse permute array dimensions.
shiftdim - Shift dimensions.
circshift - Shift array circularly.
squeeze - Remove singleton dimensions.
Array utility functions.
isscalar - True for scalar.
isvector - True for vector.
isrow - True for row vector.
iscolumn - True for column vector.
ismatrix - True for matrix.
Special variables and constants.
eps - Floating point relative accuracy.
realmax - Largest positive floating point number.
realmin - Smallest positive floating point number.
intmax - Largest positive integer value.
intmin - Smallest integer value.
flintmax - Largest consecutive integer in floating point format.
pi - 3.1415926535897....
i - Imaginary unit.
inf - Infinity.
nan - Not-a-Number.
isnan - True for Not-a-Number.
isinf - True for infinite elements.
isfinite - True for finite elements.
j - Imaginary unit.
true - True array.
false - False array.
Specialized matrices.
compan - Companion matrix.
gallery - Test matrices.
hadamard - Hadamard matrix.
hankel - Hankel matrix.
hilb - Hilbert matrix.
invhilb - Inverse Hilbert matrix.
magic - Magic square.
pascal - Pascal matrix.
rosser - Classic symmetric eigenvalue test problem.
toeplitz - Toeplitz matrix.
vander - Vandermonde matrix.
wilkinson - Wilkinson's eigenvalue test matrix.
Controlling multithreading setting.
maxNumCompThreads - Controls the maximum number of computational threads.
Matrix functions - numerical linear algebra
help matfun
Matrix functions - numerical linear algebra.
Arithmetic operators.
mpower - Matrix power ^
Matrix analysis.
bandwidth - Matrix bandwidth.
isbanded - Determine whether a matrix has certain bandwidth.
isdiag - Determine whether a matrix is diagonal.
ishermitian - Determine whether a matrix is Hermitian.
issymmetric - Determine whether a matrix is symmetric.
istril - Determine whether a matrix is lower triangular.
istriu - Determine whether a matrix is upper triangular.
norm - Matrix or vector norm.
vecnorm - Vector norm.
normest - Estimate the matrix 2-norm.
rank - Matrix rank.
det - Determinant.
trace - Sum of diagonal elements.
null - Null space.
orth - Orthogonalization.
rref - Reduced row echelon form.
subspace - Angle between two subspaces.
Linear equations.
\ and / - Linear equation solution.
linsolve - Linear equation solution with extra control.
decomposition - Linear equation solution using precomputed object.
inv - Matrix inverse.
rcond - LAPACK reciprocal condition estimator
cond - Condition number with respect to inversion.
condest - 1-norm condition number estimate.
normest1 - 1-norm estimate.
chol - Cholesky factorization.
ldl - Block LDL' factorization.
lu - LU factorization.
qr - Orthogonal-triangular decomposition.
pinv - Pseudoinverse.
lsqminnorm - Least squares with minimum norm of x.
lscov - Least squares with known covariance.
sylvester - Sylvester equation solver.
Eigenvalues and singular values.
eig - Eigenvalues and eigenvectors.
pageeig - Page-wise eigenvalues and eigenvectors.
svd - Singular value decomposition.
pagesvd - Page-wise singular value decomposition.
gsvd - Generalized singular value decomposition.
eigs - A few eigenvalues.
svds - A few singular values.
poly - Characteristic polynomial.
polyeig - Polynomial eigenvalue problem.
condeig - Condition number with respect to eigenvalues.
hess - Hessenberg form.
schur - Schur decomposition.
qz - QZ factorization for generalized eigenvalues.
ordschur - Reordering of eigenvalues in Schur decomposition.
ordqz - Reordering of eigenvalues in QZ factorization.
ordeig - Eigenvalues of quasitriangular matrices.
Matrix functions.
expm - Matrix exponential.
logm - Matrix logarithm.
sqrtm - Matrix square root.
funm - Evaluate general matrix function.
Factorization utilities
qrdelete - Delete a column or row from QR factorization.
qrinsert - Insert a column or row into QR factorization.
rsf2csf - Real block diagonal form to complex diagonal form.
cdf2rdf - Complex diagonal form to real block diagonal form.
balance - Diagonal scaling to improve eigenvalue accuracy.
planerot - Givens plane rotation.
cholupdate - rank 1 update to Cholesky factorization.
qrupdate - rank 1 update to QR factorization.
Sparse matrices
help sparfun
Sparse matrices.
Elementary sparse matrices.
speye - Sparse identity matrix.
sprand - Sparse uniformly distributed random matrix.
sprandn - Sparse normally distributed random matrix.
sprandsym - Sparse random symmetric matrix.
spdiags - Sparse matrix formed from diagonals.
Full to sparse conversion.
sparse - Create sparse matrix.
full - Convert sparse matrix to full matrix.
find - Find indices of nonzero elements.
spconvert - Import from sparse matrix external format.
Working with sparse matrices.
nnz - Number of nonzero matrix elements.
nonzeros - Nonzero matrix elements.
nzmax - Amount of storage allocated for nonzero matrix elements.
spones - Replace nonzero sparse matrix elements with ones.
spalloc - Allocate space for sparse matrix.
issparse - True for sparse matrix.
spfun - Apply function to nonzero matrix elements.
Reordering algorithms.
amd - Approximate minimum degree permutation.
colamd - Column approximate minimum degree permutation.
symamd - Symmetric approximate minimum degree permutation.
symrcm - Symmetric reverse Cuthill-McKee permutation.
colperm - Column permutation.
dmperm - Dulmage-Mendelsohn permutation.
dissect - Nested dissection permutation.
equilibrate - Matrix equilibration.
Linear algebra.
eigs - A few eigenvalues and eigenvectors.
svds - A few singular values and vectors.
ilu - Incomplete LU factorization.
ichol - Incomplete Cholesky factorization.
normest - Estimate the matrix 2-norm.
condest - 1-norm condition number estimate.
sprank - Structural rank.
Linear Equations (iterative methods).
pcg - Preconditioned Conjugate Gradients Method.
bicg - BiConjugate Gradients Method.
bicgstab - BiConjugate Gradients Stabilized Method.
bicgstabl - BiCGStab(l) Method.
cgs - Conjugate Gradients Squared Method.
gmres - Generalized Minimum Residual Method.
lsqr - LSQR Method.
minres - Minimum Residual Method.
qmr - Quasi-Minimal Residual Method.
symmlq - Symmetric LQ Method.
tfqmr - Transpose-Free QMR Method.
Operations on graphs (trees).
treelayout - Lay out tree or forest.
etree - Elimination tree.
Miscellaneous.
symbfact - Symbolic factorization analysis.
spparms - Set parameters for sparse matrix routines.
spaugment - Form least squares augmented system.
numgrid - Number the grid points in a two dimensional region.
delsq - Construct five-point finite difference Laplacian.
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
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
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
The length of a vector can also be found using the MATLAB command length
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
the first element in the vector x is the a value, then the next element is
, and so on, until b is reached A slightly more general form of the colon operator is
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.
y3 = 1:0.05:1.5 % y2 and y3 have the same values
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:
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
Try adding vectors of different sizes
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
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
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
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
% 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
in the matrix equal to 
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_c1 = transpose([1 2 3 4])
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]
Joining Matrices
You can join matrices together using square brackets [ ], provided the sizes match.
A = [r1; r2] % two row vectors, stacked on top of each other
A = [c1 c2 c3] % The matrix A has three columns joined side by side.
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, gaussianly distributed with mean value 0 and variance 1.
I4 = eye(4) % compact form, equivalent to eye(4,4)
Size of a Matrix
The dimensions (number of rows, number of columns) of a matrix can be found using the MATLAB command size
Elements of a Matrix - Indexing
In MATLAB A(i,j) accesses the element
in row i, column j of the matrix A A = zeros(3); % compact form of zeros(3, 3)
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]
Several Elements
The colon : referring to the whole row or column, can be replaced by a vector of indices
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
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]
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.
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]
p = x'*y % the dot product of x and y
Matrix Powers
Just as * represents matrix multiplication, ^ represents the multiplication of matrices together
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.
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.