You are on page 1of 61

EPE-821

Optimization and Economics of Integrated


Power Systems

Dr. Muhammad Naeem

EPE 821 Lecture 2 1


Course Outline
 Review of Math
 Basics of Optimization
 Power systems basics
 Review of Matlab
 Examples of Optimization in Power systems
 Graphical Optimization
 Optimization Types Constraint and Unconstraint
 Optimization Problem Types Linear NonLinear etc
 Linear Optimization and Power Systems Applications
 Non Linear Optimization and Power Systems Applications
 Integer and Mixed integer programming and Power Systems Applications
 Complexity Analysis EPE 821 Lecture 2 2
Set Theory
Sets A well-defined collection of objects
Subset

A={1,3,5,7,9}, B={x|x is odd}, C={1,3,5,7,9,...}

Cardinality of A=5 (|A|=5)


A B A is a proper subset of B. (If A is a subset of B, but A is not
equal to B (i.e. there exists at least one element of B which is not an
element of A)
A  B  x[ x  A  x  B ]
CB C is a subset of B. A  B  x[ x  A  x  B ]
 x[ x  A  x  B]
The power set is the set of all subsets of a given set.
For the set S = {1,2,3} this means:
P(S) = {0, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3} }
|S|=n then |P(S)| = 2n
EPE 821 Lecture 2 3
Set Theory
Sets A well-defined collection of objects
Subset

A={1,3,5,7,9}, B={x|x is odd}, C={1,3,5,7,9,...}

Cardinality of A=5 (|A|=5)


A B A is a proper subset of B. (If A is a subset of B, but A is not
equal to B (i.e. there exists at least one element of B which is not an
element of A)

CB C is a subset of B.

The power set is the set of all subsets of a given set.


For the set S = {1,2,3} this means:
P(S) = {0, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3} }
|S|=n then |P(S)| = 2n

EPE 821 Lecture 2 4


Set Theory
Conceptually, sets may be infinite (i.e., not finite, without end).
Symbols for some special infinite sets:
N = {0, 1, 2, …} The natural numbers.
Z = {…, -2, -1, 0, 1, 2, …} The integers.
R = The “real” numbers, such as 374.1828…

For real numbers a,b with a<b


[ a, b]  {x  R | a  x  b} closed interval

( a, b)  {x  R | a  x  b} open interval

[ a, b)  {x  R | a  x  b} half-open interval
( a, b]  {x  R | a  x  b} half-open interval
EPE 821 Lecture 2 5
Set Theory
For real numbers a,b with a<b
[ a, b]  {x  R | a  x  b} closed interval

( a, b)  {x  R | a  x  b} open interval

[ a, b)  {x  R | a  x  b} half-open interval
( a, b]  {x  R | a  x  b} half-open interval

 xS (“x is in S”) is the proposition that object x is an element or member


of set S.
 e.g. 3N, “a”{x | x is a letter of the alphabet}
 Can define set equality in terms of  relation:
S,T: S=T  (x: xS  xT)
“Two sets are equal iff they have all the same members.”
 xS : (xS) “x is not in S”

EPE 821 Lecture 2 6


Function
Let X and Y be two nonempty sets.
A function from X into Y is a relation that associates with each element of
X exactly one element of Y.

Domain: In a set of ordered pairs, (x, y), the domain is the set of all x-
coordinates.
Range: In a set of ordered pairs, (x, y), the range is the set of all y-
coordinates.

Example: f (x)  x5


Domain: {x: x≥5}
Range: {y: y≥0}

Example: f ( x)  x 2  5
Domain: All Real
Range: {y: y≥-5}

EPE 821 Lecture 2 7


Factorial, Permutation and Combination
For n a natural number, There are 8 choices for the first position,
n! = n(n - 1)(n - 2)·...·3·2·1 leaving 7 choices for the second slot, 6
0! = 1 choices for the third slot and so on.
n! = n(n - 1)! The number of different orderings is
1! = 1
2! = 2 8(7)(6)(5)(4)(3)(2)(1)=8! =40,320
3! = 6
4!= 3!*4 = 24
What about 10! =

Permutations are “arrangements”.


In a permutation, the order of the books is important.
Each different permutation is a different arrangement.
The arrangement ABC is different from the arrangement CBA, even
though they are the same 3 books.
The number of r-permutations of a set S with n=|S| elements is
P(n,r) = n(n−1)…(n−r+1) = n!/(n−r)
EPE 821 Lecture 2 8
Factorial, Permutation and Combination
Combinations are “selections”.
There are some problems where the order of the items is NOT
important. These are called combinations.
You are just making selections, not making different arrangements.

Example: A committee of 3 students must be selected from a group of 5


people. How many possible different committees could be formed?
Let’s call the 5 people A,B,C,D,and E.
Suppose the selected committee consists of students E, C, and A. If
you re-arrange the names to C, A, and E, it’s still the same group of
people. This is why the order is not important.
Because we’re not going to use all the possible combinations of ECA, like EAC,
CAE, CEA, ACE, and AEC, there will be a lot fewer committees. Therefore instead of
using only 5x4x3, to get the fewer committees, we must divide
(Always divide by the
5x4x3 Answer: factorial of the number of
3x2x1 EPE 821 Lecture 2digits on top of the fraction.)
10 committees 9
Factorial, Permutation and Combination
The number of r-combinations C(n,r) of a set with n=|S|
elements is

n n!
C (n, r )    
 r  r !(n  r )!

 Essentially unordered permutations …

P (n, r )  C (n, r ) P(r , r )


 Note that C(n,r) = C(n, n−r)

 n  P(n, r ) n! /( n  r )! n!
C (n, r )      
 r  P(r , r ) r! r!(n  r )!
EPE 821 Lecture 2 10
Linear Algebra
 “Algebra” means, roughly, “relationships”.
 “Linear Algebra” means, roughly, “line-like relationships”.
 If 3 feet forward has a 1-foot rise, then going 10x as far should give a 10x
rise (30 feet forward is a 10-foot rise)
 Think of a vector as a directed line segment y a 
in N-dimensions! (has “length” and   
“direction”) v v  b 
 Basic idea: convert geometry in higher
dimensions into algebra!
x
 c 
 Once you define a “nice” basis along
each dimension: x-, y-, z-axis …
 Vector becomes a 1 x N matrix!
 v = [a b c]T
 Geometry starts to become linear
algebra on vectors like v!

EPE 821 Lecture 2 11


Linear Algebra
 Vector in Rn is an ordered 1
set of n real numbers.  
6
 e.g. v = (1,6,3,4) is in R4  3
 “(1,6,3,4)” is a column  
 4
vector:  
 as opposed to a row vector:
 m-by-n matrix is an object
1 6 3 4
with m rows and n columns,
each entry fill with a real
1 2 8
number:  
 4 78 6 
9 3 2
 

EPE 821 Lecture 2 12


Linear Algebra
 Line equation: y = mx + c use the head-to-tail method A
 Matrix equation: y = Mx + c to combine vectors
 Second order equations: B
C
 xTMx = c
 y = (xTMx)u + Mx
B

 … involves quadratic forms like xTMx


A
Vector Addition: A+B
av
A  B  ( x1 , x2 )  ( y1 , y2 )  ( x1  y1 , x2  y2 )
av  a ( x1 , x2 )  (ax1 , ax2 ) v
Scalar Product: A+B

Change only the length (“scaling”), but keep direction fixed.

Matrix operation (Av) can change length, direction and also dimensionality!

EPE 821 Lecture 2 13


Linear Algebra
Vectors: Magnitude (Length) and Phase (direction)

v  ( x1 , x2 ,  , xn ) T
n
v  x
2
i
(Magnitude or “2-
i 1
norm”)
If v  1, v is a unit vector

(unit vector => pure direction) Alternate representations:


Polar coords: (||v||, )
y
Complex numbers: ||v||ej

||v||


“phase”
x
EPE 821 Lecture 2 14
Linear Algebra
Vector norm
Forann-dimensionalvector x  [ x1 x2 ... xn ]
1/ p
 p
thevectornorm: x p  x p
   xi  ; p  1, 2,...
 i 
Specialcase : x   max xi
i

Mostcommonlyused L2  norm : x 2  x  x12  x2 2  ...xn 2

Example: v = (1, 2, 3) Properties:


Name Symbol value
1. x  0when x  0; x  0iff  x  0
L1 – norm |v|1 6
2. kx  k x scalark
L2 – norm |v|2 14  3.74
1/2

3. x  y  x  y
L3 – norm |v|3 361/33.3
L – norm |v| 3

EPE 821 Lecture 2 15


Linear Algebra
 5 0 1  5  (stretching)
     
 0 5 1  5 
 0  11   1
      (rotation)
 1 0 1  1 

 0 1  1   0  (reflection)
     
 1 0  0   1 

 1 0 1  1  (projection)
     
 0 0 1  0 

 1 c  x   x  cy  (shearing)
     
 0 1  y   y 
EPE 821 Lecture 2 16
Linear Algebra
Matrices as sets of constraints x y z 1  x
 1 1 1   1 
  y    
2  1 1  z   2 
Special matrices 2x  y  z  2 
 

 a 0 0 a b c a b 0 0 1 0 0
    a 0 0    
 0 b 0  0 d e   c d e 0  0 1 0 
0 0 b c 0 0 f g h 0 0 1
0 0 c f  d    
    e f  0
 0 i j 

diagonal upper-triangular lower-triangular tri-diagonal I (identity matrix)

 Transpose of A: Matrix obtained by interchanging rows and columns of A.


 Denoted by A’ or AT. AT = [aji]
1 4
2 5 
 AT = 
 3 6 

 Symmetric Matrix: AT = A
 Identity Matrix: A square matrix whose diagonal elements are all 1 and off-
diagonal elements are all zero. Denoted by I.
 Null Matrix: A matrix whose all elements are zero.
EPE 821 Lecture 2 17
Linear Algebra
Determinants
Example Evaluate the determinant of

3 5 3 5
A  det A   (3)( 2)  (5)(1)  6  5  1
1 2  1 2
Def: Minors
Let A =[aij] be an nxn matrix . The ijth minor of A ( or the minor of
aij) is the determinant Mij of the (n-1)x(n-1) submatrix after you
delete the ith row and the jth column of A.
Example Find M 23 , M 32 , M 33 , 1 0 2 
A  4 3 1
3 5 1

EPE 821 Lecture 2 18


Linear Algebra
Def: Cofactors
Let A =[aij] be an nxn matrix . The ijth cofactor of A ( or the
i j
cofactor of aij) is defined to be Aij  (1) M ij
Example Find A23 , A32 , A33 , signs
1 0 2     
  
A  4 3 1   
3 5 1     

Def: Cofactor matrix


Let A =[aij] be an nxn matrix . The cofactor matrix = [Aij]
Example Find the cofactor matrix signs
   
1 0 2    
A  4 3 1   
   
3 5 1 

EPE 821 Lecture 2 19


Linear Algebra
0 2 1
A   3  1 2
4 0 1
 Find all the minors and cofactors of A, and then find the
determinant of A.
 Sol: 1 2 3 2 3 1
M 11   1, M 12   5, M 13 
4
0 1 4 1 4 0
C11  1 C12  5 C13  4
M 21  2, M 22  4, M 23  8, C21  2, C22  4, C23  8,
M 31  5, M 32  3, M 33  6. C31  5, C32  3, C33  6.
A  a11C11  a12C12  a13C13  0(1)  2(5)  1(4)  14
 a21C21  a22C22  a23C23  3(2)  (1)( 4)  2(8)  14
 a11C11  a21C21  a31C31  0(1)  3(2)  4(5)  14
EPE 821 Lecture 2 20
Linear Algebra
Principal Minor

 Principal minor of order k: A sub-matrix obtained by deleting any n-k


rows and their corresponding columns from an n x n matrix Q.
1 2 3 
 Consider Q  4 5 6
7 8 9

 Principal minors of order 1 are diagonal elements 1, 5, and 9.

 Principal minors of order 2 are 1 2 1 3 5 6


4 5, 7 9 and 8 9
 Principal minor of order 3 is Q.      
 Determinant of a principal minor is called principal determinant.

 There are 2n-1 principal determinants for an n x n matrix.

EPE 821 Lecture 2 21


Linear Algebra
Leading Principal Minor
 The leading principal minor of order k of an n x n matrix is obtained
by deleting the last n-k rows and their corresponding columns.
1 2 3
 Q  4 5 6
7 8 9
 Leading principal minor of order 1 is 1.
 Leading principal minor of order 2 is 1 2 
4 5
 
 Leading principal minor of order 3 is Q itself.
 No. of leading principal determinants of an n x n matrix is n.

EPE 821 Lecture 2 22


Linear Algebra
 Tests for positive definite matrices
 All diagonal elements must be positive.
 All the leading principal determinants must be positive.
 Tests for positive semi-definite matrices
 All diagonal elements are non-negative.
 All the principal determinants are non-negative.
 Tests for negative definite and negative semi-definite matrices
 Test the negative of the matrix for positive definiteness or positive
semi-definiteness.
 Test for indefinite matrices
 At least two of its diagonal elements are of opposite sign.

EPE 821 Lecture 2 23


Linear Algebra

EPE 821 Lecture 2 24


Linear Algebra
Eigenvalues
If the action of a matrix on a (nonzero) vector changes its magnitude but
not its direction, then the vector is called an eigenvector of that matrix. A
vector which is "flipped" to point in the opposite direction is also
considered an eigenvector. Each eigenvector is, in effect, multiplied by a
scalar, called the eigenvalue corresponding to that eigenvector. The
eigenspace corresponding to one eigenvalue of a given matrix is the set of
all eigenvectors of the matrix with that eigenvalue
Given a linear transformation A, a non-zero vector x is defined to be an
eigenvector of the transformation if it satisfies the eigenvalue equation

AX   X
for some scalar λ. In this situation, the scalar λ is called an eigenvalue of
A corresponding to the eigenvector x.

EPE 821 Lecture 2 25


Linear Algebra
Computation of eigenvalues, and the characteristic equation
When a transformation is represented by a square matrix A, the
eigenvalue equation can be expressed as

AX   IX  0
Solve det(A − λI) = 0.

EPE 821 Lecture 2 26


Linear Algebra

EPE 821 Lecture 2 27


Linear Algebra

EPE 821 Lecture 2 28


Linear Algebra

EPE 821 Lecture 2 29


Linear Algebra

EPE 821 Lecture 2 30


Linear Algebra

EPE 821 Lecture 2 31


Linear Algebra

EPE 821 Lecture 2 32


Differential Calculus
The derivative, or derived function of f(x) denoted f`(x) is
defined as
 f ( x  h)  f ( x ) 
f `( x)  lim  
h 0
 h 
y
Q
f ( x  h)  f ( x )
P f ( x  h)  f ( x )
h mPQ 
h
x x+h x

  y  dy
Leibniz Notation: f `( x)  lim EPE 821Lecture
 2 33
h o  x
  dx
Calculus

The Product Rule


If k ( x)  f ( x).g ( x) , then: k `( x)  f `( x) g ( x)  g `( x) f ( x)

If y  f ( x).g ( x), then:


dy df dg dy
 .g ( x )  . f ( x ) OR  f `g  g ` f
dx dx dx dx

1. Differentiate y  x 2 sin x

f ( x)  x 2 g ( x)  sin x dy
 f `g  g ` f  2 x sin x  x 2 cos x
f `( x)  2 x g `( x)  cos x dx

EPE 821 Lecture 2 34


Calculus
The Quotient Rule
dy f `g  g ` f

dx g2

d  x3 
1. Find  
dx  sin x 

f ( x)  x3 g ( x)  sin x

f `( x)  3 x 2 g `( x)  cos x

dy f `g  g ` f 3 x 2 sin x  x3 cos x
 2

dx g sin 2 x

EPE 821 Lecture 2 35


Calculus
A secant line is a straight line joining two points on a function

A tangent line is a straight line that touches a function at only one point.
The tangent line represents the instantaneous rate of change of the
function at that one point. The slope of the tangent line at a point on the
function is equal to the derivative of the function at the same point.

EPE 821 Lecture 2 36


36
Calculus
A stationary point is an input to a
function where the derivative is zero
Stationary points (red circles) and
inflection points (blue squares).
The stationary points in this graph
are all relative maxima or relative
minima.
An inflection point or Saddle point , is
a point on a curve at which the
curvature or concavity changes sign
from plus to minus or from minus to
plus.
A critical point of a function is
any point (a, f(a)) where f `(a) =
0 or where f `(a) does not exist.
f(x) = x2 + 2x + 3 is differentiable everywhere
 f(x) = x2/3 is defined for all x and differentiable
for x ≠ 0, with the derivative f′(x) = 2x−1/3/3.
EPE 821 Lecture 2 37
Calculus 5
y

Consider the function:


4


 x2  2  x  1 3

 2

f ( x)   x 1 x  2
1 1

 x 1 2  x  4
2
– 2 – 1 1 2 3 4 x

– 1

Domain [2, 4) – 2


2 x  2  x 1

f `( x)  1 1 x  2
1
 2 x4
2 EPE 821 Lecture 2 38
 Calculus 
 x2  2  x  1 2 x  2  x 1
 
f ( x)   x 1 x  2 f `( x)  1 1 x  2
1 1
 x 1 2  x  4  2 x4
2 2
y
Critical points are:
5

A (-2,4) f `(-2) does not exist.


A 4
(Right differentiable at x = -2)
3 E
2 D B (0,0) f `(0) = 0. (Turning point)

1 C C (1,1) f `(1) does not exist. Left


derivative =2, right derivative = 1
B
– 2 – 1 1 2 3 4 x

– 1
D (2,2) f `(2) does not exist. Left
– 2 derivative = 1, right derivative = 0.5

E is not a critical point as it is notEPE


in 821
theLecture
domain2 of f. 39
Local extrema Calculus 43215– 21
321– 321

Local extreme values occur either at the end points of the function, turning
points or critical points within the interval of the domain.
y

Consider the function, 5

 x2  2x  3  x  1 4

 3
f ( x)   x 1  x  1 3

2 x 2  8 x  5 1  x  3 2

 1

Domain [3,3)
–3 –2 –1 1 2 3 x

3 is the local maximum value –1

-1 is the local minimum value –2

If extrema occurs at end points then they are end point maximums or end
point minimums.
(i) Local maximum / minimum turning points
(ii) End point values
(iii) Critical points
EPE 821 Lecture 2 40
Calculus
The Nature of Stationary Points.
If f `(a) = 0 then a table of values over a suitable interval centred at a
provides evidence of the nature of the stationary point that must exist at a.
A simpler test does exist.
It is the second derivative test.

f `( x )  0 and f ``( x )  0 then minimum turning point.


f `( x )  0 and f ``( x )  0 then maximum turning point.
f `( x )  0 and f ``( x )  0 then draw a table of signs.
If the second derivative test is easier to determine than making a table of
signs then this provides an efficient technique to finding the nature of
stationary points.

EPE 821 Lecture 2 41


Calculus
100
Orig
80 1st Derv.
2nd Derv.
60
y = x 4-4x 3+5
40 dy = 4 x. 3 - 12*x2
d2y = 12 x 2 - 24 x
20

y
0

-20

-40

-60

x = -2:0.001:4; -80
-2 -1 0 1 2 3 4
y = x.^4 - 4*x.^3 + 5; x

dy = 4 * x.^3 - 12*x.^2;
d2y = 12 * x.^2 - 24*x;

plot(x,y,'r','LineWidth',2); hold on;


plot(x,dy,'b','LineWidth',2); hold on;
plot(x,d2y,'k','LineWidth',2); hold on;
legend('Orig','1st Derv.','2nd Derv.')
EPE 821 Lecture 2 42
Graph Theory
 Network = graph
 Informally a graph is a set of nodes joined 1 2 3 1 2 3
by a set of lines or arrows.
 Nodes and edges 4 5 6
4 5 6
 G(V, E)
 Undirected graph
 Directed graph
 V:={1,2,3,4,5,6}
 E:={{1,2},{1,5},{2,3},{2,5},{3,4},{4,5},{4,6}}
 Many problems can be stated in terms of a graph
 The properties of graphs are well-studied
 Many algorithms exists to solve graph problems
 Many problems are already known to be intractable

 By reducing an instance of a problem to a standard graph problem, we may be


able to use well-known graph algorithms to provide an optimal solution
 Graphs are excellent structures for storing, searching, and retrieving large
amounts of data
 Graph theoretic techniques play an important role in increasing the
storage/search efficiency of computational
EPE 821 Lecture 2techniques. 43
Graph Theory
Undirected graph Directed graph

loop loop

G=(V,E)
isolated vertex
adjacent
multiple
edges
 incidence: an edge (directed or undirected) is incident to a vertex that is
one of its end points.
 degree of a vertex: number of edges incident to it
 Nodes of a digraph can also be said to have an indegree and an
outdegree
 adjacency: two vertices connected by an edge are adjacent

EPE 821 Lecture 2 44


Graph Theory

x y a
path: no vertex can be repeated
example path: a-b-c-d-e e
b
trail: no edge can be repeated
example trail: a-b-c-d-e-b-d
walk: no restriction
example walk: a-b-d-a-b-c d
closed: if starting vertex is also ending c
vertex
length: number of edges in the path, trail,
or walk

circuit: a closed trail (ex: a-b-c-d-b-e-d-a)


cycle: closed path (ex: a-b-c-d-a)
EPE 821 Lecture 2 45
Graph Theory
 simple graph: an undirected graph with no loops or multiple edges
between the same two vertices
 multi-graph: any graph that is not simple
 connected graph: all vertex pairs are joined by a path
 disconnected graph: at least one vertex pairs is not joined by a path
 complete graph: all vertex pairs are adjacent
 Kn: the completely connected graph with n vertices

Simple graph a
a e
b
e
b
K5
d
c d
Disconnected graph
with two components c
EPE 821 Lecture 2 46
Graph Theory
 acyclic graph (forest): a graph with no cycles
 tree: a connected, acyclic graph
 rooted tree: a tree with a “root” or “distinguished” vertex
 leaves: the terminal nodes of a rooted tree
 directed acyclic graph (DAG): a digraph with no cycles
 weighted graph: any graph with weights associated with the edges
(edge-weighted) and/or the vertices (vertex-weighted)

b 10 a

5
d 8 c

2 -3
e f
6

EPE 821 Lecture 2 47


MathTerminologies
 Theorem — a mathematical statement that is proved using rigorous
mathematical reasoning. In a mathematical paper, the term theorem is
often reserved for the most important results.
 Lemma — a minor result whose sole purpose is to help in proving a
theorem. It is a stepping stone on the path to proving a theorem.
 Corollary — a result in which the (usually short) proof relies heavily on a
given theorem (we often say that “this is a corollary of Theorem A”).
 Proposition — a proved and often interesting result, but generally less
important than a theorem.
 Conjecture — a statement that is unproved, but is believed to be true.
 Axiom/Postulate — a statement that is assumed to be true without proof.
These are the basic building blocks from which all theorems are proved
EPE 821 Lecture 2 48
In a nutshell
MathTerminologies
A Theorem is a major result
A Corollary is a theorem that follows on from another theorem
A Lemma is a small results (less important than a theorem)
Example: Here is a Theorem, a Corollary to it, and also a Lemma!
Theorem: Corollary
If m and n are any two whole numbers and a, b and c, as defined above, are
• a = m  – n
2 2
a Pythagorean Triple
• b = 2mn Proof:
• c = m2 + n2 From the Theorem a2 + b2 = c2, so
then a2 + b2 = c2 a, b and c are a Pythagorean Triple
Proof: (That result "followed on" from the
a2 + b2 = (m2 – n2)2 + (2mn)2 previous Theorem.)

= m4 – 2m2n2 + n4 + 4m2n2 Lemma: If m = 2 and n = 1, then we get the


Pythagorean triple 3, 4 and 5
= (m2 + n2)2 Proof: If m = 2 and n = 1, then
= c2 a = 22 – 12 = 4 – 1 = 3
b = 2 × 2 × 1 = 4
(That was a "major" result.) c = 22 + 12 = 4 + 1 = 5
(That was a "small" result.)
EPE 821 Lecture 2 49
MathTerminologies
 Proposition — a proved and often interesting result, but generally less
important than a theorem.  if x is odd then x2 is odd.
 Conjecture — a statement that is unproved, but is believed to be true.
 Every even number larger than 2 can be written as a sum of two primes.
 Axiom/Postulate — a statement that is assumed to be true without proof.
These are the basic building blocks from which all theorems are proved.
One of the axioms of arithmetic is that a + b = b + a. You can’t prove that,
but it is the basis of arithmetic and something we use rather often.

EPE 821 Lecture 2 50


MATLAB
 MATLAB is an interactive environment
 Commands are interpreted one line at a time
 Commands may be scripted to create your own functions or
procedures
 Variables are created when they are used
 Variables are typed, but variable names may be reused for different
types
 Basic data structure is the matrix
 Matrix dimensions are set dynamically
 Operations on matrices are applied to all elements of a matrix at
once
 Removes the need for looping over elements one by one!
 Makes for fast & efficient programmes

EPE 821 Lecture 2 51


MATLAB
 A MATLAB matrix is a rectangular array of numbers
 Scalars and vectors are regarded as special cases of matrices
 MATLAB allows you to work with a whole array at a time

 You can also use built in functions to create a matrix


 >> A = zeros(2, 4)
 creates a matrix called A with 2 rows and 4 columns
containing the value 0
 >> A = zeros(5) or >> A = zeros(5, 5)
 creates a matrix called A with 5 rows and 5 columns

 You can also use:


 >> ones(rows, columns)
 >> rand(rows, columns)

 Note: MATLAB always refers to the first value as the number of


Rows then the second as the number of Columns

EPE 821 Lecture 2 52


MATLAB
 The colon : is actually an operator, that generates a row vector
 This row vector may be treated as a set of indices when accessing a
elements of a matrix
 The more general form is
 [start:stepsize:end]
 >> [11:2:21]
 11 13 15 17 19 21
 >>
 Stepsize does not have to be integer (or positive)
 >> [22:-2.07:11]
 22.00 19.93 17.86 15.79 13.72 11.65

EPE 821 Lecture 2 53


MATLAB
 Mathematical Operators:
 Add: +
 Subtract: -
 Divide: ./
 Multiply: .*
 Power: .^ (e.g. .^2 means squared)

 You can use round brackets to specify the order in which


operations will be performed
 Note that preceding the symbol / or * or ^ by a ‘.’ means
that the operator is applied between pairs of
corresponding elements of vectors of matrices

EPE 821 Lecture 2 54


MATLAB
Combining this with methods from Accessing Matrix Elements gives
way to more useful operations
>> results = zeros(3, 5)
>> results(:, 1:4) = rand(3, 4)
>> results(:, 5) = results(:, 1) + results(:, 2) + results(:, 3) + results(:, 4)
or
>> results(:, 5) = results(:, 1) .* results(:, 2) .* results(:, 3) .* results(:, 4)

EPE 821 Lecture 2 55


MATLAB
 Logical Operators:
 Greater Than: >
 Less Than: <
 Greater Than or Equal To: >=
 Less Than or Equal To: <=
 Is Equal: ==
 Not Equal To: ~=

For example, you can find data that is above a certain limit:
>> r = results(:,1)
>> ind = r > 0.2

Boolean Operators:
AND: &
OR: |
NOT: ~
EPE 821 Lecture 2 56
MATLAB
 There are a number of special functions that provide useful
constants
 pi = 3.14159265….
 i or j = square root of -1
 Inf = infinity
 NaN = not a number
 Passing a vector to a function like sum, mean, std will calculate the property within
the vector
 >> sum([1,2,3,4,5])
 = 15
 >> mean([1,2,3,4,5])
 =3
 >> max([1,2,3,4,5])
 =5

EPE 821 Lecture 2 57


MATLAB
 The plot function can be used in different ways:
 >> plot(data)
 >> plot(x, y)
 >> plot(data, ‘r.-’)
 In the last example the line style is defined
 Colour: r, b, g, c, k, y etc.
 Point style: . + * x o > etc.
 Line style: - -- : .- 1

0.8

 A basic plot
0.6

0.4

 >> x = [0:0.1:2*pi] 0.2

0
 >> y = sin(x) -0.2

 >> plot(x, y, ‘r.-’) -0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7
EPE 821 Lecture 2 58
MATLAB
 For command
 Use a for loop to repeat one or more statements

 The end keyword tells Matlab where the loop finishes

 You control the number of times a loop is repeated by defining the


values taken by the index variable

 This uses the colon operator again, so index values do not need
to be integer

 For example
 >> for i = 1:4
 a(i) = i * 2
 end

EPE 821 Lecture 2 59


MATLAB
 The counter can be used to index different rows or columns
 E.g.
 >> results = rand(10,3)
 >> for i = 1:3
 m(i) = mean(results(:, i))
 end
 ..although you could do this in one step
 m = mean(results);

EPE 821 Lecture 2 60


MATLAB
 The ‘if’ command is used with logical operators
 Again, the end command is used to tell Matlab where the statement
ends.
 For example, the following code loops through a matrix performing
calculations on each column
 >> for i = 1:size(results, 2)
 m = results(:, i)
 if m > 1
 do something
 else
 do something different
 end
 end

EPE 821 Lecture 2 61

You might also like