You are on page 1of 63

Computational Methods in

Chemical Engineering

LECTURE 2
FUNDAMENTALS: ARRAYS

ÖZGE KÜRKÇÜOĞLU-LEVİTAS
Introduction

 Array: a fundamental form to store and manipulate data.


 It is a list of numbers arranges in rows and/or columns.
 Simplest array: 1-D
 Row or column of numbers
 More complex array: 2-D
 Collection of numbers arranged in rows and columns

 In science and engineering:


 1-D arrays: represents “vectors”

 2-D arrays: represents “matrices”


Notes about Variables in MATLAB

 All variables in MATLAB are arrays.


 Scalar: Array with one element
 Vector: Array with one row or column
 Matrix: Array with elements in rows and columns

 There is no need to define the size of array before elements are


assigned. Variable is defined by input when variable is assigned.
 Once a variable exists, it can be changed to any other size of variable.
 Scalar to vector/matrix

 Vector to scalar/vector of different length/matrix etc.

 That can be made by adding or deleting elements.


Creating 1-D Array (Vector)

 1-D array:
 A list of numbers arranged in a row or a column.
 Any list of numbers can be set up as a vector.
 In MATLAB: A vector is created by assigning the elements of
the vector to a variable.
 This can be done in several ways depending on the source of
information
Creating 1-D Array (Vector)

Creating a vector from a known list of numbers:


 The vector is created by typing the elements (numbers) inside
square brackets [ ].
variable_name = [ type vector elements ]

 Row vector: To create a row vector, type the elements with a space or a
comma (,) between elements inside the square brackets.
 Column vector: To create a column vector, type the left square bracket [ and
then enter the elements with a semicolon (;) between them, or press enter
key after each element. Type the right square bracket ] after the last element.
>> r_vector=[1 2 3 4 5]

r_vector =
1 2 3 4 5

>> c_vector=[1;2;3;4;5]

c_vector =
1
2
3
4
5
Creating 1-D Array (Vector)

Creating a vector with constant spacing by specifying the first term,


the spacing, and the last term:
 In a vector with constant spacing, the difference between the elements is the
same. Ex: v = 2 4 6 8 10, spacing is 2.

 Vector in which the first term is m, the spacing is q, and the last
term is n is created by typing:
variable_name = [ m:q:n ] or variable_name = m:q:n
 If the numbers are so that the value n cannot be obtained by adding q’s to m,
 Last element in the vector is last number that does not exceed n.
 If only two numbers (first and list terms) are typed,
 The default for spacing is 1.
>> A=[0:2:6]
A=
0 2 4 6

>> A=0:2:6
A=
0 2 4 6

>> A=0:2:5
A=
0 2 4

>> A=0:6
A=
0 1 2 3 4 5 6
Creating 1-D Array (Vector)

Creating a vector with linear (equal) spacing by specifying the first


and last terms, and the number of terms:
• Vector with n elements that are linearly (equally) spaced in which
the first element is xi and the last element is xf can be created by
typing the “linspace” command:
variable_name = linspace(xi, xf, n)
• Then MATLAB determines the correct spacing
• When the number of elements omitted
• The default is 100
x = linspace(a,b,N+1);
is equivalent to:
x = a : (b-a)/N : b;
N+1 equally-spaced points in the interval [a,b]
or
dividing [a,b] into N equal sub-intervals
>> x = linspace(1,5,6)

x=

1.0000 1.8000 2.6000 3.4000 4.2000 5.0000


similarly
>> y=1:0.8:5

y=

1.0000 1.8000 2.6000 3.4000 4.2000 5.0000

x = a : s : b;
the number of subintervals within [a,b] is obtained by rounding (b-a)/s,
down to the nearest integer,
N = floor((b-a)/s);
length(x) is equal to N+1
x(n) = a + s*(n-1),
n = 1,2,...,N+1
How to call array entries?

 In Matlab, array index starts from 1.


>> y=1:0.8:5
y=
1.0000 1.8000 2.6000 3.4000 4.2000 5.0000
y(1) y(2) y(3) y(4) y(5) y(6)

>> y(4)
ans =
3.4000

 In C/C++ and Fortran index can start from 0


Built-in Functions For Handling Arrays

 MATLAB has many built-in functions for managing and handling


arrays.
 Some examples:
 length(A), size(A), diag(A), sum(A)

 max(A), min(A), sort(A)

 mean(A), mode(A), std(A), median(A)

 radn, randn % random number generators

 clock, date

 factorial(n), nthroot(n)
sin(x), cos(x), tan(x), cot(x)
asin(x), acos(x), atan(x), acot(x)
sinh(x), cosh(x), tanh(x), coth(x)
asinh(x), acosh(x), atanh(x), acoth(x)

exp(x), log(x), log10(x), log2(x)


Additional built-in functions for
floor(x), ceil(x), round(x) manipulation of arrays are described in the
Help Window.
sqrt(x), abs(x) Select “Functions by Category,”
sum(x), cumsum(x) Then “Mathematics,”
Then “Arrays and Matrices.”
Adding Elements to Existing Variables

 A variable that exists as a vector, or a matrix, can be changed by adding


elements to it.

Adding elements to a vector:


 Elements can be added to an existing vector by assigning values to the
new elements.
 If a vector has n elements and a new value is assigned to an element with an
address of n+2 or larger,
 MATLAB assigns zeros to elements that are between the last original element
and the new element.

 Elements can also be added to a vector by appending existing vectors


>> z=[3 0.5 6 1 24 sqrt(16)]
z=
3.0000 0.5000 6.0000 1.0000 24.0000 4.0000

>> length(z) >> z(end-3:end) %last 4 elements


ans = ans =
6 6 1 24 4

>> z(end) >> z(3:5) % from third to fifth element


ans = ans =
4 6 1 24

>> z(1:3:end) %every third element


ans =
3 1
>> z(end:-1:1) % in reverse order
ans =
4.0000 24.0000 1.0000 6.0000 0.5000 3.0000

>> z([3 1 5]) % z(3) z(1) z(5)


ans =
6 3 24

>> newz=z([3 1 5]) % assign a new variable newz


newz =
6 3 24

>> z(1)=9; % assign a new value to existing entry


>> z
z=
9.0000 0.5000 6.0000 1.0000 24.0000 4.0000
Repetitive Calculations

• With element-by-element calculations you can easily evaluate a


formula repeatedly for a large set of data.
• This is one of MATLAB’s most useful and powerful features.
• Example:
• Calculate y = x2-4x for x = [1:8]
• Calculate y = (z3+5z)/(4z2-10) for z = [1:2:11]
>> x = [0, pi/4, pi/3, pi/2, pi];
>> sin(x)
ans =
0 0.7071 0.8660 1.0000 0.0000

>> x = [2.1, 2.8, -3.1, -3.5, 4.5];


>> y = exp(x)
y=
8.1662 16.4446 0.0450 0.0302 90.0171

>> z = log(y) % note log(exp(x)) = x


z=
2.1000 2.8000 -3.1000 -3.5000 4.5000
>> [fix(x); floor(x); ceil(x); round(x)]
ans =
2 2 -3 -3 4
2 2 -4 -4 4
3 3 -3 -3 5
2 3 -3 -4 5
Vector Addition & Subtraction

• Addition (+) & subtraction (-) :


• Element-by-element operations
• Performed on corresponding elements

 c = a + b → ei = ai + bi i = 1, . . . , n
 d = a − b → fi = ai − ci i = 1, . . . , n
Example:

 When a scalar is added to (substracted from) a vector, the scalar is


added to (substracted from) all elements of the vector.
Multiplication by a Scalar

 Multiplication by a scalar involves multiplying each element in


the vector by the scalar
 c = σ * a → ci = σ * ai i = 1, . . . , n

Example:
Linear Combinations
Vector Dot Product

• In physics, analytical geometry and engineering, the “dot product” has a


geometric interpretation
[x1 x2 x3]
θ
[y1 y2 y3]

• Syntax:
C = dot(A,B) returns the scalar product of the vectors A and B.
A and B must be vectors of the same length.
When A & B are both row vectors, dot(A,B) is same as A*B’.
• Example
a = [1 2 3]; b = [4 5 6];
c = dot(a,b)
c = 32 Corresponds to: sum(a.*b)
Vector Inner Product

 The rules of linear algebra impose compatibility requirements on the


inner product
 The “inner product” of x and y requires that x be a row vector y be a
column vector

 In Matlab: The * operator performs inner product if vectors are


compatible
 >> u = [0 1 2 3]; >> v = [3 2 1 0]; % two vectors
>> s = u * v' >> t = u * v
s= ??? Error using ==> mtimes
4 Inner matrix dimensions must agree.
Vector Outer Product

 The inner product results in a scalar


 The “outer product” creates a rank-one matrix
 a = u * vT → ai,j = ui * vj
Creating 2-D Array (Matrix)

 2-D array: Also called a matrix


 Has numbers in rows and columns
 Plays important role in linear algebra

 In a square matrix: Number of rows and columns are equal.


 In general: number of rows and columns can be different.
 A “m x n” matrix:
 Has m rows and n columns,
 Size of matrix m by n.
Creating 2-D Array (Matrix)

 Matrix is created by assigning elements of matrix to a variable.


 Done by typing the elements, row by row, inside square brackets
[ ].
 First, type left bracket [,

 Then type first row elements (with spaces or commas)

 To type next row, type a semicolon or press “Enter”

 Type right bracket ] at the end of last row

variable_name = [ 1st row elements; 2nd row elements; .....; last


row elements ];
Creating 2-D Array (Matrix)

 Elements can be numbers or mathematical expressions that may


include numbers, predefined variables and functions
 All the rows must have the same number of elements.
 If an element is zero, it has to be entered as such.
 MATLAB displays an error message if an attempt is made to
define an incomplete matrix.
 Rows of a matrix can also be entered as vectors using the notation
for creating vectors with constant spacing or “linspace”
command.
Array Addressing

Matrix
 Address of an element in a matrix
 Its position defined by the row number and the column number
 For a matrix named ma, ma(k,p) refers to the element in row k and column p.

Ex:

ma(1,1) = 3 and ma(2,3) = 10

 It is possible to change the value of just one element of a matrix by assigning a


new value to that element.
 Also, single elements can be used like variables in mathematical expressions
and functions.
>> A = [ 3 2 1 ; 5 1 0 ; 2 1 7 ]

A=

3 2 1
5 1 0
2 1 7

Access the elements:


>> A(2,3) %row 2, column 3

ans =

0
Using a Colon

 Colon (:) can be used to address a range of elements in vector/matrix


For a vector:
 v(:) : Refers to all the elements of the vector v (either a row or a column
vector).
 v(m:n) : Refers to elements m through n of the vector v.

For a matrix:
 A(:,n) : Refers to the elements in all the rows of column n of the matrix A.
 A(n,:) : Refers to the elements in all the columns of row n of the matrix A.
 A(m:n,p:q) : Refers to the elements in rows m through n and columns p
through q of the matrix A.
 New vectors and matrices can be created from existing ones by using a range of
elements, or a range of rows and columns (using :)
 It is also possible to select only specific elements, or specific rows and columns
of existing variables to create new variables.
 This is done by typing the selected elements or rows or columns inside brackets.
: means from … to …
A=
3 2 1
5 1 0
2 1 7

>> A(3,2:3) >> A(:,:)


ans = ans =
1 7 3 2 1
5 1 0
>> A(:,2) 2 1 7
ans =
2 >> A(3,:)
1 ans =
1 2 1 7
Adding Elements to Existing Variables

Adding elements to a matrix:


 Rows and/or columns can be added to an existing matrix by assigning values
to the new rows or columns.
 This can be done
 by assigning new values,

 by appending existing variables.

 Must be done carefully since the size of the added rows/columns must fit the
existing matrix.
 If a matrix has a size of m x n, and a new value is assigned to an element with
an address beyond the size of the matrix, MATLAB increases the size of the
matrix to include the new element.
 Zeros are assigned to the other elements that are added.
Deleting Elements

 An element, or a range of elements, of an existing variable can be


deleted by reassigning nothing to these elements.
 This is done by using square brackets with nothing typed in between
them.
 By deleting elements, a vector can be made shorter and a matrix can be
made to have a smaller size.
Matrix Operations

Similarities with vectors


 Addition and subtraction
 c = a + b → ci,j = ai,j + bi,j i = 1, . . , m & j = 1, . . , n

 Multiplication by a Scalar
 c = σ * a → ci,j = σ * ai,j i = 1, . . , m & j = 1, . . , n

 Note: Commas in subscripts are necessary when the subscripts


are assigned numerical values. For example, a2,3 is the row 2,
column 3 element of matrix A, whereas a23 is the 23rd element of
vector a.
Operation Matrix-wise Element-wise
Addition + +
Substraction - -
Multiplication * .*
Right Division / ./
Left Division \ .\
Exponentiation ^ .^
Transpose w/o complex conjugation .‘
Transpose with complex conjugation ‘
Matrix Multiplication

 Multiplication operation (*) is executed by MATLAB according


to the rules of linear algebra.
 Matrix multiplication results in an array where each element is a
dot product
 In general, the results are found by taking the dot product of each
row in matrix A with each column in matrix B
Matrix Multiplication

• Matrix–vector product
looks like

• Vector–matrix product
looks like

• Matrix–matrix product
looks like
Matrix Multiplication

• Matrix multiplication is a series of


dot products.

• Number of columns in matrix A


must equal number of rows in
matrix B.
• Result is a matrix that has the
same number of rows as A and the
same number of columns as B.
Matrix Multiplication

Matrix multiplication is not


commutative

F*G does not equal G*F


Matrix Division

 Division operation is also associated with the rules of linear


algebra.
 It is a complex operation and only a brief explanation is given
here.
 Division operation can be explained with the help of identity
matrix and the inverse operation.
Identity Matrices

• Identity matrix is a square matrix with ones on the main diagonal.

• When identity matrix multiplies another matrix (or vector), that matrix
(or vector) is unchanged.
AI = A and IA = A for any compatible matrix A
• This is like multiplying by 1 in scalar arithmetic
Matrix Inverse

 Matrix B is the inverse of matrix A (A-1), if, when the two matrices are
multiplied, the product is the identity matrix.
 A matrix times its inverse is the identity matrix
 A* A-1 = 1
 To have an inverse, a matrix must be square
 MATLAB offers two approaches
 The matrix inverse function:
 inv(A)
 Raising a matrix to the -1 power:
 A-1
Matrix Inverse
Determinants

 The MATLAB function to find a determinant is


 det(A)
 Related to the matrix inverse
 If the determinant is equal to 0, the matrix does not have an inverse
 Not all matrices have an inverse
 Singular
 Ill-conditioned matrices
 Attempting to take the inverse of a singular matrix results in an error
statement
Left Division

 Left division is used to solve the matrix equation AX = B. In this


equation X and B are column vectors.
 AX = B → A-1AX = A-1B
 So, the solution of AX = B is
X = A-1B
 Solve this problem in Matlab using
 Matrix inverse approach
X = inv(A)*B
Easy, but not efficient computationally
 Matrix left division using Gaussian elimination
X=A\B
More efficient & less prone to round-off error
Example

• Solving by using left division

• Solving by using the inverse


Right Division

 Right division is used to solve the matrix equation XC = D. In this


equation X and D are row vectors.
 Right divison is used to solve the matrix equation
XC = D
 XCC-1 = DC-1

 So, the solution is


X = DC-1

 Solve this problem in Matlab


X = D/C
Example

•Solving by using right division

•Solving by using the inverse


Element-by-Element Operations

 When regular symbols for multiplication and division are used


with arrays:
 Mathematical operations follow rules of linear algebra.
 However, many situations require element-by-element operations.
 Already element-by-element operations by definitions:
 Addition and substraction
 Element-by-element multiplication etc. is entered in
MATLAB by typing a period “.” in front of arithmetic
operator.
 Array multiplication .*
 Array division ./
 Array exponentiation .^
!!! In each case the size of the arrays must match !!!
• Multiplication/division between
arrays is performed on corresponding
elements if the “.” operator is used
g = a .* c → gi = ai * ci i = 1, . . . , n
h = a ./ c → hi = ai / ci i = 1, . . . , n
Transpose Operator

 When applied to a vector:


 Switches a row (column) vector to a column (row) vector.
 When applied to a matrix:
 Switches rows (columns) to columns (rows)

 Applied by typing a single quote “ ' ” following the variable to be


transposed.
>> A
A=
1 2 3
2 0 4
0 8 5

>> A'
ans =
1 2 0
2 0 8
3 4 5
Examples

A= B=
1 2 3 1 3 1
2 0 4 4 9 5
0 8 5 2 7 2

>> A’ % transpose
>> B*A % matrix multiplication
>> B.*A % element by element multiplication
>> B/A % matrix division
>> B./A % element by element division
>> [B A] % Join matrices (horizontally)
>> [B; A] % Join matrices (vertically)
A= B=
1 2 3 1 3 1 >> B./A
2 0 4 4 9 5 ans =
>> B*A 0 8 5 2 7 2 1.0000 1.5000 0.3333
ans = 2.0000 Inf 1.2500
7 10 20 Inf 0.8750 0.4000
22 48 73
16 20 44 >> [B A]
ans =
>> B.*A 1 3 1 1 2 3
ans = 4 9 5 2 0 4
1 6 3 2 7 2 0 8 5
8 0 20
0 56 10 >> [B;A]
ans =
>> B/A 1 3 1
ans = 4 9 5
11.5000 -5.2500 -2.5000 2 7 2
34.5000 -15.2500 -7.5000 1 2 3
25.5000 -11.7500 -5.5000 2 0 4
0 8 5
A=
1 2 3
2 0 4
0 8 5

>> A^2 % same as A*A >> 2*A


ans =
ans =
5 26 26 2 4 6
2 36 26 4 0 8
16 40 57 0 16 10

>> A.^2
ans =

1 4 9
4 0 16
0 64 25
>> C=[1 2; 3 4] >> D= 10.^C

C= D=
1 2 10 100
3 4 1000 10000

>> [C, C.^2; C^2, C*C] >> [D, log10(D)]


ans =
ans = 10 100 1 2
1 2 1 4 1000 10000 3 4
3 4 9 16
7 10 7 10
15 22 15 22
A= >> B=[10;5;-1]
1 2 3
2 0 4 B=
0 8 5 10
5
>> inv(A) -1
ans =
>> X=A\B % uses Gauss elimination,
8.0000 -3.5000 -2.0000 more efficient, less error
2.5000 -1.2500 -0.5000 X=
-4.0000 2.0000 1.0000 64.5000
19.2500
>> A*inv(A) -31.0000
ans =
>> Y=inv(A)*B % easy but not efficient
1 0 0 Y=
0 1 0 64.5000
0 0 1 19.2500
-31.0000
zeros, ones, eye Commands

 They can be used to create matrices that have elements with


special values.
 zeros (m,n): matrix with m row and n columns in which all elements are the
numbers 0
 ones (m,n): matrix with m row and n columns in which all elements are the
numbers 1
 eye(n): creates a square matrix with m row and n columns in which th diagonal
elements are equal to 1 and the rest of elements are 0. It is called the “identity
matrix”.

 Matrices can also be created as a result of mathematical


operations with vectors and matrices (next week)
Generation of random numbers

rand, rand(1,n), rand(n), rand(m,n), randi, randn

>> x=randn(3,4) % pseudorandom values drawn


% from the standard normal distribution
x=
0.5377 0.8622 -0.4336 2.7694
1.8339 0.3188 0.3426 -1.3499
-2.2588 -1.3077 3.5784 3.0349

>> y=rand(2,3) % from interval (0,1)


y=
0.9572 0.8003 0.4218
0.4854 0.1419 0.9157
x=
0.5377 0.8622 -0.4336 2.7694
1.8339 0.3188 0.3426 -1.3499
-2.2588 -1.3077 3.5784 3.0349

>> [m,i] = min(x), min(min(x))


m=
-2.2588 -1.3077 -0.4336 -1.3499 % minimum of each column
i=
3 3 1 2 % corresponding indices in each column
ans =
-2.2588 % overall minimum

>> sort(x) % sort column-wise


ans =
-2.2588 -1.3077 -0.4336 -1.3499
0.5377 0.3188 0.3426 2.7694 Also try these:
1.8339 0.8622 3.5784 3.0349 sort(x,'ascend')
sort(x,'descend')
>> A = [1 2 3; 2 0 4; 0 8 5]
A=
1 2 3
2 0 4
0 8 5

>> size(A) % values of M (row) and N (column)


ans =
3 3
>> sum(A)
ans =
>> diag(A)
3 10 12
ans =
1
>> sum(1./A(1,:))
0
ans =
5
1.8333
>> mean(A)
ans =
>> cumsum(1./A(1,:))
1.0000 3.3333 4.0000
ans =
1.0000 1.5000 1.8333
>> mean(A(1,:))
ans =
2

You might also like