Sei sulla pagina 1di 37

ESG

111
Numerical Methods for
Chemical Engineering Analysis
WEEK 2
Vectors and Matrices

Matrices

MATLAB stands for matrix laboratory


A matrix is used to store a set of values of the same type
Every value is stored in an element
A matrix looks like a table; it has both rows and columns
The dimensions of a matrix are r x c (pronounced r by c)
r: number of rows, c: the number of columns
9

This matrix is 2 x 3
(2 rows by 3 columns)

The term array is frequently used in MATLAB to refer generically to a


matrix or a vector
emaGcs, the general form of an r x c matrix A is wriIen as;
!
#
#
A =#
#
#"

a11

a12

a21

a22

"
"
am1 am2

! a1n $
&
! a2n &
& = aij (i = 1,, m
"
" &
! amn &%

j = 1,, n)

Vectors and Scalars


A vector is a special case of a matrix in which one of the dimensions
is 1
a row vector with n elements is 1 x n


5
88
3
11

a column vector with n elements is n x 1
3
column vector with
7
dimensions 3 x 1

row vector with


dimensions 1 x 4

A scalar is an even more special case ; its dimension is 1 x 1 (just a


single value!)
5

A vector is a one-dimensional array


A matrix is a two-dimensional array

CreaGng Row Vectors


Direct method: put the values you want in square brackets, separated
by either commas or spaces
>> vr
v =
1
>> vr
v =
1

= [1

4]

2 3 4
= [1,2,3,4]
2

Colon operator: iterates through values in the form of m:c:n (m:first


value, c:step, n:last valuet)
If no step is specied, the default is 1
Can go in reverse

Ex 1) vec1=5:3:14
Ex 2) vec2=2:4
Ex 3) vec3=4:-1:1
Ex 4) vec4=1:2:8

CreaGng Column Vectors


Direct method: put the values you want in square brackets,
separated by semicolons
>>vc=[4; 7; 2]

You cannot directly create a column vector using the colon


operator :
You can create a row vector and then transpose it to get a
column vector using the transpose operator
The rows and columns are interchanges by
Ex) vec8=vec7

Referring to elements: same as row vectors; specify indices in


parentheses

CreaGng Matrix Variables


Separate values within rows with blanks or commas, and
separate the rows with semicolons or by hibng the ENTER
key
Can use any method to get values in each row (any method to
create a row vector, including colon operator)
>> mat = [1:3; 6 11 -2]
mat =
1 2 3
6 11 -2

There must ALWAYS be the same number of values in


every row!!

FuncGons linspace, logspace


The funcGon linspace creates a linearly spaced vector
linspace(x,y,n) creates a vector with n values in the inclusive
range from x to y (including x and y)
creates a vector with 3 values
including the 4 and 7 so it
ex) >>vec5=linspace(4,7,3)
returns [4 5.5 7]
If n is omiIed, the default is 100 points
The funcGon logspace creates a logarithmically spaced vector
logspace(x,y,n) creates a vector with n values in the inclusive
range from 10^x to 10^y
returns [ 100 1000
10000]
ex) >>logspace(2,4,3)
If n is omiIed, the default is 50 points

ConcatenaGon
Vectors can be created by joining exisGng vectors and
valuables, or adding elements to exisGng vectors
This is called concatena3on
For example:
>> v = 2:5;
Try this!
>> x = [33 11 2];

>> w = [v x]
>>w=[v; x]
w =
>>w=[v; x 44]
2 3 4 5 33 11 2
>> newv = [v 44]
newv =
2 3 4 5 44

Ex) CreaGng Vector & Matrix


vec1 = [ 5 8 11 14]
vec2 = [ 2 3 4]
vec3 = [ 4 3 2 1]
vec4 = [1 3 5 7]

vec5 =

5
8
11
14

vec6= [ vec1 vec2 ]

1 2 3

mat1 = 4 5 6
7 8 9

1 4 7

mat2 = 2 5 8
3 6 9

vec3
mat3 =

vec4

5 8 11 14 44
mat4 =

2 3 4 5 6

Referring to Elements
The elements in a vector are numbered sequenGally
each element number is called the index, or subscript
1
2
3
4
5

index (subscript)
5
33
11
-4
2

elements
An element in a vector can be accessed by using its index or
subscript in parentheses

Ex) vec(4) is the 4th element of a vector vec (assuming it has at least 4
elements)

A subset of a vector can be obtained by using the colon operator


Ex) vec(1:4) refers to the rst 4 elements

index vector which is a vector of indices e.g. vec([m n]) refers to the
mnd and nth elements of vec
! The indices dont need to be sequenGal

[ ] shows the index


of the vector

Matrix Elements
To refer to an element in a matrix, you use the matrix variable
name followed by the index of the row, and then the index of
the column, in parentheses
>> mat = [1:3; 6 11 -2]
mat =
1 2 3
6 11 -2
Refers to the value in the
>> mat(2,1)
2nd row, 1st column
ans =
6

Ex)
>>mat(1:2,2:3)

*refers to the 1st&2nd row,
2nd&3rd column

ALWAYS refer to the row rst, column second


This is called subscripted indexing
Can also refer to any subset of a matrix
To refer to the enGre mth row: mat(m,:)
To refer to the enGre nth column: mat(:,n)

Matrix Indexing
To refer to the last row or column use end
mat(end,m) is the mth value in the last row
Can modify an element or subset of a matrix in an
assignment statement
Linear indexing: only using one index into a matrix
(MATLAB will unwind it column-by column)
MATLAB stores matrices in memory in column
major order (columnwise)
" 11 23 35 %
Ex) mat = $
' element
# 62 114 26 & index

Linear indexing refers to


the elements in order by
columns

Modifying Vectors
Elements in a vector can be changed
Ex) >>vec5(3) = 11
A vector can be extended by referring to elements that do not
yet exist
If there is a gap between the end of the vector and the new
specied element(s), zeros are lled in
Ex) >> vec7 = [3 9];
Original vec7 has 2 elements
>> vec7(4:6) = [33 2 7]
We add index 4 to 6, thus 0 is
vec7 =
lled in index3
3 9 0 33 2 7
*Extending vectors is not a good idea if it can be avoided

Modifying Matrix
An individual element in a matrix can be modied
by assigning a new value
An enGre row or column can be changed by using
the colon operator
Any subset of a matrix can be modied as long as
assigned subset has the same number of rows and
columns

An individual element can not be added in a


matrix
An enGre row or column can be added

FuncGons that create matrices


There are many built-in funcGons to create matrices
rand(n) creates an nxn matrix of random reals
rand(n,m) create an nxm matrix of random reals
randi([range],n,m) creates an nxm matrix of random integers
in the specied range
zeros(n) creates an nxn matrix of all zeros
zeros(n,m) creates an nxm matrix of all zeros
ones(n) creates an nxn matrix of all ones
ones(n,m) creates an nxm matrix of all ones
Note: there is no twos funcGon or thirteens just zeros and
ones!

Matrix Dimensions
There are several funcGons to determine the dimensions of a vector or
matrix:
length(vec) returns the # of elements in a vector
length(mat) returns the larger dimension (row or column) for a matrix
size returns the # of rows and columns for a vector or matrix
To capture the values of the size, put a vector of 2 variables on the ler of an
assignment statement
[r c] = size(mat)

numel returns the total # of elements in a vector or matrix

Very important to be general in programming:


that you
know the dimensions of a vector or matrix use length or size to nd out!

# of element in a vector
length, numel
# of element of row and column in a matrix

size

FuncGons that change dimensions


Many funcGon change the dimensions of a matrix:
reshape changes dimensions of a matrix to any matrix with the
same number of elements
rot90 rotates a matrix 90 degrees counter-clockwise

rot90(mat,n) rotate 90*n degree (n: posiGve/


negaGve)
iplr ips columns of a matrix from ler to right
ipud ips rows of a matrix up to down
n
! mat1 ! mat1 $
repmat replicates a matrix; creates m x n copies of the matrix
]
[
] &
# [
Ex) >>mat2=repmat(mat1,m,n)

mat2 =

#
!
!
#
#" [ mat1] !

&
!
&
mat1
[
] &
%

Empty Vectors
An empty vector is a vector with no elements
an empty vector can be created using square brackets with nothing
inside [ ]
An element can be added in an empty vector
Empty vectors can also be used to grow a vector, starGng with
nothing and then adding to the vector by concatenaGng values to it
(usually in a loop, which will be covered later)
This is not ecient, however, and should be avoided if possible

to delete an element from a vector, assign an empty vector to that


element
delete an enGre row or column from a matrix by assigning [ ]
cannot delete an individual element from a matrix

3D Matrices
A three dimensional matrix has dimensions m x n x p
m: # of rows, n: # of columns, p: # of layers

Can create using built-in funcGons


Ex) the following creates a 3 x 5 x 2 matrix of random
integers; there are 2 layers, each of which is a 3 x 5 matrix
>> randi([0 50], 3,5,2)
ans(:,:,1) =
36
34
6
17
38
33
25
29
14
8
48
11
ans(:,:,2) =
35
27
13
41
45
7
42
12
48
7
12
47

38
13
25
17
10
1

Layer 1

Layer 2
Copyright 2013 Elsevier Inc. All rights
reserved

20

Arrays as funcGon arguments


EnGre arrays (vectors or matrices) can be passed as
arguments to funcGons; this is very powerful!
The result will have the same dimensions as the
input
For example:
>> vec = randi([-5 5], 1, 4)
vec =
-3 0 5 1
>> av = abs(vec)
av =
3 0 5 1

Try this!
>>mat3 = randi([-10 10], 3)

>>sin(mat3)

Powerful Array FuncGons


There are a number of very useful funcGon that
are built-in to perform operaGons on vectors, or
on columns of matrices:

min the minimum value


max the maximum value
sum the sum of the elements
prod the product of the elements
cumsum cumulaGve, or running sum as it iterates
through the elements
cumprod cumulaGve, or running product as it iterates
through the elements

min, max Examples


>> vec = [4 -2 5 11];
>> min(vec)
ans =
-2
>> mat = randi([1, 10], 2,4)
mat =
6 5 7 4
3 7 4 10
>> max(mat)
ans =
6 7 7 10

Note: the result is a scalar when the argument is a vector; the result is a 1 x n
vector when the argument is an m x n matrix

sum, cumsum vector Examples


The sum funcGon returns the sum of all
elements; the cumsum funcGon shows the
running sum as it iterates through the elements
(4, then 4+-2, then 4-2+5, and nally 4-2+5+11)
>> vec = [4 -2 5 11];
>> sum(vec)
ans =
18
>> cumsum(vec)
ans =
4 2 7 18

sum, cumsum matrix Examples


For matrices, the funcGons operate column-wise:
>> mat = randi([1, 10], 2,4)
mat =
1 10 1 4
9 8 3 7
>> sum(mat)
ans =
10 18 4 11
>> cumsum(mat)
ans =
1 10 1 4
10 18 4 11

The sum is the sum for each column; cumsum


shows the cumulaGve sums as it iterates through
the rows

prod, cumprod Examples


These funcGons have the same format as sum/cumsum, but
calculate products
>> v = [2:4 10]
v =
2 3 4 10
>> cumprod(v)
ans =
2 6 24 240
>> mat = randi([1, 10], 2,4)
mat =
2 2 5 8
8 7 8 10
>> prod(mat)
ans =
16 14 40 80

Overall funcGons on matrices


Since these funcGons operate column-wise for
matrices, it is necessary to nest calls to them in
order to get the funcGon for all elements of a
matrix,
>> mat = randi([1, 10], 2,4)
mat =
9 7 1 6
4 2 8 5
>> min(mat)
ans =
4 2 1 5
>> min(min(mat))
ans =
1

Scalar operaGons
Numerical operaGons can be performed on every element in
a vector or matrix
For example, Scalar mul3plica3on: mulGply every element by
a scalar
>> [4 0 11] * 3
ans =
12 0 33

Another example: scalar addiGon; add a scalar to every


element
>> zeros(1,3) + 5
ans =
5 5 5

Array OperaGons
Array opera3ons on two matrices A and B:
these are applied term-by-term, or element-by-element
this means the matrices must have the same dimensions
In MATLAB:
matrix addiGon: A + B
matrix subtracGon: A B or B A

For operaGons that are based on mulGplicaGon (mulGplicaGon,


division, and exponenGaGon), a dot must be placed in front of
the operator
array mulGplicaGon: A .* B
array division: A ./ B, A .\ B
array exponenGaGon A .^ 2

matrix mulGplicaGon: NOT an array operaGon; see next slide

Matrix MulGplicaGon: Dimensions


Matrix mul3plica3on is NOT an array operaGon
it does NOT mean mulGplying term by term
In MATLAB, the mulGplicaGon operator * performs matrix mulGplicaGon
Matrix mulGplicaGon has a very specic deniGon
In order to be able to mulGply a matrix A by a matrix B, the number of
columns of A must be the same as the number of rows of B
If the matrix A has dimensions m x n, that means that matrix B must
have dimensions n x p (p can be any dimension)
In mathemaGcal notaGon, [A]m x n [B]n x p
The inner dimensions (As column# and Bs row#, n) must be the
same
The resulGng matrix C has the same number of rows as A and the same
number of columns as B
The outer dimensions is m x p
In mathemaGcal notaGon, [A]m x n [B]n x p = [C]m x p
This only denes the size of C; it does not explain how to calculate
the values

Matrix MulGplicaGon
The elements of the matrix C are found as follows:
the sum of products of corresponding elements in
the rows of A and columns of B

cij =
EX)

aik bkj

k =1

The 35, for example, is obtained by


taking the rst row of A and the rst
column of B, mulGplying term by term
and adding these together. In other
words, 3*1 + 8*4 + 0*0, which is 35.

! 1 2 3 1 $
! 3 8 0 $ #
& ! 35 46 17 19 $
#
&# 4 5 1 2 & = #
&
" 1 2 5 % # 0 2 3 4 & " 9 22 20 5 %
"
%

Vector OperaGons
Since vectors are just special cases of matrices,
the matrix operaGons described including
addiGon, subtracGon, scalar mulGplicaGon,
mulGplicaGon, and transpose work on vectors as
well, as long as the dimensions are correct
Specic vector operaGons:
The dot product or inner product of two vectors a and
b is dened as a1b1 + a2b2+ a3b3 + + anbn
built-in funcGon dot to do this

Also, cross for cross product

Logical Vectors
Using relaGonal operators on a vector or matrix results in a logical
vector or matrix

Use relaGonal expressions that result


>> vec = [44 3 2 9 11 6];
in true/false
>> logv = vec > 6
logical sentence
logv =
1 0 0 1 1 0
The result is the vector with the same length as the

Logical Indexing

original, but the type is logical (not double)

can use this to index into a vector or matrix (only if the index vector
is the type logical)
>> vec(logv)
ans =
44 9 11

Only element from the original matrix/vector


which is logical true are returned.

True/False
false equivalent to logical(0)
true equivalent to logical(1)
false and true are also funcGon that create matrices
of all false or true values
EX1) >>false(3)

EX2) >>true(1,7)

ans =
0
0
0

ans =
0
0
0

0
0
0

Logical Built-in FuncGons


any returns true if anything in the input argument is true
all returns true only if everything in the input argument is true
nd nds locaGons and returns indices
>> vec
vec =
44 3 2 9 11 6
>> nd(vec>6)
ans =
1 4 5

Comparing Arrays
The isequal funcGon compares two arrays,
and returns logical true if they are equal (all
corresponding elements) or false if not
>> v1 = 1:4;
>> v2 = [1 0 3 4];
>> isequal(v1,v2)
ans =
0
>> v1 == v2
ans =
1 0 1 1
>> all(v1 == v2)
ans =
0

If the two arrays are


not the same
dimension,
- isequal return
logical 0
- == returns error

Equality operator ==
will return 1 or 0 for
each element
all funcGon will return
all elements are equal
or not

Element-wise operators, or and


| and & are used for matrices; go through
element-by-element and return logical 1 or 0
|| and && are used for scalars

FuncGons di and meshgrid


di returns the dierences between consecuGve
elements in a vector and operate on each column
for a matrix
meshgrid receives as input arguments two
vectors, and returns as output arguments two
matrices that specify separately x and y values
>> [x y] = meshgrid(1:3,1:2)
x =
1 2 3
1 2 3
y =
1 1 1
2 2 2

Potrebbero piacerti anche