You are on page 1of 43

Arrays

Tan Do

Vietnamese-German University

Lecture 2

Tan Do (VGU) Introduction to MATLAB Lecture 2 1 / 43


Content

In this lecture

Array denition, array classes and data types


Variable editor
Element-by-element operations on arrays
Vector operations: scaling, dot product, cross product
Matrix multiplication
Some special matrices
Character array.
sprintf command and script le.

Tan Do (VGU) Introduction to MATLAB Lecture 2 2 / 43


Denition

Denition

An array is a list of items arranged in rows and/or columns.


For examples,
" #
h i 23 4 9
1 3 −1 4 19 0.5 π and are arrays of numbers.
2 0 2
2 Alex is an array of characters (called a string).
 
Alex 4912
3  Bob 4879 is a mixed array of numbers and characters.
 

Charlie 5120
Arrays play fundamental role in MATLAB.
Every information and data are represented as arrays in MATLAB.

Tan Do (VGU) Introduction to MATLAB Lecture 2 3 / 43


Vectors

Row vector

A one-dimensional array is called a vector.

5 9 0 is a row vector.
h i

In MATLAB, type
» [5 9 0]
ans =
5 9 0
Commas are used to improve readability.
» [5, 9, 0]
ans =
5 9 0

Tan Do (VGU) Introduction to MATLAB Lecture 2 4 / 43


Vectors

 
1
−4 is a column vector.
 
 
7
In MATLAB, type
» [1; -4; 7]
ans =
1
-4
7

Note that semicolons are used in the above command.


You can also type
» [1 -4 7]’ or » [1, -4, 7]’
to get the same result. ' is called the transpose operator.
Tan Do (VGU) Introduction to MATLAB Lecture 2 5 / 43
Matrices

Matrices

A two-dimensional array is called a matrix.


" #
1 2
is a 2 × 2 (square) matrix.
3 4

In MATLAB, type

» [1 2; 3 4]
ans =
1 2
3 4

Tan Do (VGU) Introduction to MATLAB Lecture 2 6 / 43


Matrices

" #
−3 4 6
is a 2 × 3 matrix.
7 1 0
 
−2 8
 is a 3 × 2 matrix.
 
0 1
 
9 37
Generally, a table of numbers with m rows and n columns is called an
m × n matrix.
 
a11 a12 a13 ... a1n
 
 a21 a22 a23 . . . a2n 
 
a
 31 a32 a33 . . . a3n 

 . .. .. .. 
 .
 . . . . 

am1 am2 am3 . . . amn


An m × n matrix
Tan Do (VGU) Introduction to MATLAB Lecture 2 7 / 43
Arrays of higher dimensions

Multidimensional arrays

The idea above can be extended to dene arrays of higher dimensions


called multidimensional arrays.
For example, we can think of a three-dimensional array as a stack of several
layers of matrices with dimension m × n × p.
Here m is the number of rows, n the number of columns as with a matrix.
The higher dimension p is the number of layers of matrices.

A multidimensional array
Tan Do (VGU) Introduction to MATLAB Lecture 2 8 / 43
Classication

Array classes
So far we have discussed arrays involving numbers only. These are called
numeric arrays.
More classes of arrays are available in MATLAB:

1 Numeric arrays: Items are numbers.


2 Character arrays: Items are strings of alphabets.
3 Logical arrays: Items are TRUE or FALSE values (logical values).
4 Structure arrays
5 Cell arrays
6 Function handles
7 Java arrays

In this course, we will cover arrays of types [1], [2] and [6].
Tan Do (VGU) Introduction to MATLAB Lecture 2 9 / 43
Numeric arrays

Numeric arrays
A numeric array is an array whose elements are numbers.
In MATLAB there are several types of numbers.
single single-precision real number (oating point),
occupies 32 bits in computer memory
double double-precision real number (oating point),
occupies 64 bits in computer memory
int8, uint8 signed and unsigned 8-bit integer respectively
int16, uint16 signed and unsigned 16-bit integer respectively
...
The default numeric type in MATLAB is double.
It is possible to change from one numeric type to another. But this is not
advisable, unless you are told to do so.
Tan Do (VGU) Introduction to MATLAB Lecture 2 10 / 43
Numeric arrays

More ways of creating vectors


Previously we discussed some basic ways of creating vectors.
Here we mention some more.

To create a vector with regularly spaced elements, the syntax is


» v = a:s:b
This will create a vector v with spacing s (also called step size).
The rst value is a and
(
b if b − a is a multiple of s,
the last value =
less than b otherwise.

If we type
» v = a:b
then the step size s is set to 1.
Tan Do (VGU) Introduction to MATLAB Lecture 2 11 / 43
Numeric arrays

Example
» 0:2:10
ans =
0 2 4 6 8 10

» 0:2:9
ans =
0 2 4 6 8

» 1:0.2:2
ans =
1.0000 1.2000 1.4000 1.6000 1.8000 2.0000

» -3:2
ans =
-3 -2 -1 0 1 2
Tan Do (VGU) Introduction to MATLAB Lecture 2 12 / 43
Numeric arrays

» 6:-2:1
ans =
6 4 2

The linspace command also creates a vector of regularly spacing


elements. But the syntax is a little dierent.
» linspace(a, b, n)
where a is the initial value, b the nal value and n the number of points.

Example
» linspace(1, 2, 6)
ans =
1.0000 1.2000 1.4000 1.6000 1.8000 2.0000
If n is omitted, the spacing is 1.

Tan Do (VGU) Introduction to MATLAB Lecture 2 13 / 43


Numeric arrays

Appending vectors
We can append one vector to another.

Example
» a = [1 2 3]; b = [4 5 6];
» v = [a, b]
ans =
1 2 3 4 5 6
M = [a; b]
ans =
1 2 3
4 5 6

Note the eect of the comma and the semicolon in the above example.
Tan Do (VGU) Introduction to MATLAB Lecture 2 14 / 43
Numeric arrays

Magnitude, length and absolute value of a vector


Let v = (v1 , v2 , . . . , vn ) be a vector.

The magnitude of v is dened to be v12 + v22 + . . . + vn2 .


p

In MATLAB, the command is


» norm(v)

The length of v is the number of elements in v , i.e., n.


In MATLAB, type
» length(v)

The absolute value of v is a vector of the same length whose elements are
absolute values of elements in v correspondingly.
In MATLAB, type
» abs(v)
Tan Do (VGU) Introduction to MATLAB Lecture 2 15 / 43
Numeric arrays

Example
» v = [1, 0 , -1, -5]
v =
1 0 -1 -5

» norm(v)
ans =
5.1962

» length(v)
ans =
4

» abs(v)
ans =
1 0 1 5
Tan Do (VGU) Introduction to MATLAB Lecture 2 16 / 43
Numeric arrays

Matrices and the transpose operator

Let M be an m × n matrix.
The transpose M T of M is an n × m matrix whose rows are the columns
of M correspondingly.  
" # 1 0
1 −1 8
For example, if M = , then M T =  .
 
−1 4
0 4 −2  
8 −2
In MATLAB, type
» M = [1, -1, 8; 0, 4, -2]
M =
1 -1 8
0 4 -2

Tan Do (VGU) Introduction to MATLAB Lecture 2 17 / 43


Numeric arrays

» M’
ans =
1 0
-1 4
8 -2
Recall ' is called the transpose operator.

Note that a row vector of length n can be considered as a 1 × n matrix.

Similarly, a column vector of length n can be considered as a n × 1 matrix.

Tan Do (VGU) Introduction to MATLAB Lecture 2 18 / 43


Numeric arrays

Array addressing

To address an element of a vector, we use the position of that element in


the vector.
For example, if v = [1, −2, 3, 7], then

v1 = 1, v2 = −2, v3 = 3 and v4 = 7.

In MATLAB, type
» v = [1, -2, 3, 7];
v(4)
ans =
7

Tan Do (VGU) Introduction to MATLAB Lecture 2 19 / 43


Numeric arrays

To get a range of elements, type


» v(2:4)
ans =
-2 3 7
which gives the elements from the second to the fourth position of v .

Tan Do (VGU) Introduction to MATLAB Lecture 2 20 / 43


Numeric arrays

To address an element of a matrix, row and column numbers are used.


These are called indices of that element.
" #
1 −1
For example, if M = , then
0 9

M11 = 1, M12 = −1, M21 = 0 and M22 = 9.

Note the way we index the elements of M : the rst index is the row
number and the second index is the column number.

In MATLAB, type
» M = [1, -1; 0, 9];
» M(1,2)
ans =
-1
Tan Do (VGU) Introduction to MATLAB Lecture 2 21 / 43
Numeric arrays

Next suppose that M is a 4 × 5 matrix. Then

M(:,2) gives the second column of M .

M(2,:) gives the second row of M .

M(:,2:5) gives the columns of M from position 2 to 5.

M(2:3,3:5) gives all elements Mij with 2 ≤ i ≤ 3 and 3 ≤ j ≤ 5.

M(:) stacks all columns of M into one single column vector.

M(end,:) gives the last row in M and M(:,end) gives the last
column in M .

Tan Do (VGU) Introduction to MATLAB Lecture 2 22 / 43


Numeric arrays

Empty array

An empty array contains no element in it.


To obtain an empty array in MATLAB, type
» []
ans =
[]

We can delete rows and columns in a matrix M using the empty array.

Example
M(:,2) = [] deletes column 2.
M(:,3:5) = [] deletes columns from position 3 to 5.
M(:,[1, 3, 5]) = [] deletes columns in positions 1, 3 and 5.
Tan Do (VGU) Introduction to MATLAB Lecture 2 23 / 43
Numeric arrays
" #
1 7 3
Suppose M = .
5 9 6

Then typing
» M(4,2) = 21

results in

ans =
1 7 3
5 9 6
0 0 0
0 21 0

i.e., MATLAB expands the size of M and adds zeros to ll out the
remaining elements.

Tan Do (VGU) Introduction to MATLAB Lecture 2 24 / 43


Numeric arrays

Useful array functions


Function Description
length(A) returns number of elements if A is a vector
returns max{m, n} if A is an m × n matrix
max(A) Vector: returns the largest element
Matrix: returns a row vector of largest element in each column of A
min(A) same as max(A) but returns smallest values instead
sort(A) Vector: sorts elements of A in ascending order
Matrix: sorts elements of each column of A in ascending order
sum(A) Vector: sums all elements of A and returns a number
Matrix: sums all elements in each column of A and
returns a vector of these sums in corresponding order
size(A) returns the vector [m n] of the array A of size m × n
find(A) returns a column vector of the indices of non-zero elements in A
Tan Do (VGU) Introduction to MATLAB Lecture 2 25 / 43
Numeric arrays

Some variants of the above functions are


Function Description
[x,k] = max(A) same as max(A) but stores max values in vector x
and corresponding row indices in vector k
[x,k] = min(A) same as [x,k] = max(A), returns min values instead
sort(A,’descend’) sorts A in descending order
sort(A,dim,mode) the general syntax for sort command
dim stands for dimension along which to sort,
1 along row and 2 along column
mode is either 'ascending' (by default) or 'descending'
[u,v,w] = find(A) returns w containing non-zero elements of A,
u containing row indices of the non-zero elements,
v containing column indices of the non-zero elements

Tan Do (VGU) Introduction to MATLAB Lecture 2 26 / 43


Element-by-element operations

Element-by-element operations

Symbol Operation Form Example


+ Scalar array addition A+b [1,5] + 3 = [4,8]
Array addition A+B [-1,0] + [4,8] = [3,8]
 Scalar array subtraction A-b [1,5]  3 = [-2,2]
Array subtraction A-B [-1,0]  [4,8] = [-5,-8]
.* Array multiplication A.*B [5,2] .* [7,3] = [35,6]
./ Array right division A./B [5,2] ./ [7,3] = [5/7,2/3]
.\ Array left division A .\B [5,2] .\ [7,3] = [5\7,2\3]
.b Array exponentiation A.bB [3,5].b2 = [32 , 52 ]
2.b[3,5] = [23 , 25 ]
[3,5].b[2,4] = [32 , 54 ]

Tan Do (VGU) Introduction to MATLAB Lecture 2 27 / 43


Matrix operations

Vector scaling
To change the magnitude of a vector, we multiply it by a scalar.
In MATLAB, type
» u = [5, -3, 7];
» 4*u
ans =
20 -12 28
The same idea is also applied to matrices. For example,
» M = [2, 3; 5, -1];
» 2*M
ans =
4 6
10 -2
Tan Do (VGU) Introduction to MATLAB Lecture 2 28 / 43
Matrix operations

Dot product

The dot product of two vectors u = [u1 , u2 , . . . , un ] and


v = [v1 , v2 , . . . , vn ] is dened by

u · v = u1 v1 + u2 v2 + . . . + un vn .

MATLAB syntax for dot product is dot(u,v).

Example
» u = [1,2,3]; v = [5,2,0];
» dot(u,v)
ans =
9

Tan Do (VGU) Introduction to MATLAB Lecture 2 29 / 43


Matrix operations

Cross product

The cross product of two vectors u = [u1 , u2 , u3 ] and v = [v1 , v2 , v3 ] is


another vector w in such a way that w is perpendicular to both u and v
whose direction follows the right-hand rule.
In notation w = u × v .
Algebraically

u × v = [u2 v3 − u3 u2 , u3 v1 − u1 v3 , u1 v2 − u2 v1 ].

(a) Cross product (b) Right-hand rule

Tan Do (VGU) Introduction to MATLAB Lecture 2 30 / 43


Matrix operations

MATLAB syntax for cross product is cross(u,v).

Example
» u = [1,2,3]; v = [5,2,0];
» cross(u,v)
ans =
-6 15 -8

Note that cross product is only dened for vectors in 3 dimensions.

Tan Do (VGU) Introduction to MATLAB Lecture 2 31 / 43


Matrix operations

Matrix multiplication

Next we will dene the multiplication of two matrices A and B .

First we dene the multiplication of a row vector by a column vector.


 
v1
 
 v2 
[u1 , u2 , . . . , un ] ∗  .  = u1 v1 + u2 v2 + . . . + u3 v3 .
 
 .. 
 
vn

Note the similarity between this and the dot product.

Tan Do (VGU) Introduction to MATLAB Lecture 2 32 / 43


Matrix operations

Let A be an m × n matrix and B an n × r matrix.


Note that the number of column of A is the same as the number of row of
B.
Dene M = [mij ] = A ∗ B , where

mij = i-th row of A ∗ j-th column of B.

Example
 
" # 3 0 " #
1 2 3   2 33
∗ −2 9 = .
4 5 6   8 75
2×3 1 5 2×2
3×2
" # " #
1 h i 7 3
∗ 7 3 = .
2 1×2 14 6
2×1 2×2

Tan Do (VGU) Introduction to MATLAB Lecture 2 33 / 43


Matrix operations

In MATLAB, type
» A = [1, 2, 3; 4, 5, 6]; B = [3, 0; -2, 9; 1, 5];

» A*B
ans =
2 33
8 75

» u = [1, 2]; v = [7; 3];

» u*v
ans =
7 3
14 6

Tan Do (VGU) Introduction to MATLAB Lecture 2 34 / 43


Matrix operations

Special matrices
The zero matrix has all entries equal to 0. We denote the zero matrix by 0.
For example,
 
" # " # 0 0 0
0 0 0 0 0
, , 0 0 0 , ...
 
0 0 0 0 0
0 0 0

are zero matrices.


The identity matrix is a square matrix which has 1's along the diagonal and
all 0's elsewhere. We denote the identity matrix by I.
For example,  
" # 1 0 0
1 0
, 0 1 0 , ...
 
0 1
0 0 1
are identity matrices.
Tan Do (VGU) Introduction to MATLAB Lecture 2 35 / 43
Matrix operations

The zero and identity matrices have the following properties.

0A = A0 = 0, IA = AI = A

for all square matrix A.


More special matrices are also available in MATLAB.

Command Description
eye(n) creates an n × n identity matrix
zeros(n) creates an n × n zero matrix
zeros(m,n) creates an m × n zero matrix
zeros(size(A)) creates a zero matrix the same size as matrix A
ones(n) creates an n × n matrix whose entries are all 1's
ones(m,n) creates an m × n matrix whose entries are all 1's
ones(size(A)) creates a matrix of 1's the same size as matrix A

Tan Do (VGU) Introduction to MATLAB Lecture 2 36 / 43


char arrays

Character encoding

Characters include letters of the alphabet, digits, punctuation marks,


white space and control characters.

White space characters include the space, tab, etc.


Control characters include are characters that cannot be printed, but
accomplish a task (e.g., a backspace or enter)

A character in MATLAB is represented using single quotes.

Example 'a' and '3' are characters.

The single quotes are essential to denote a character. Without them,


a letter is interpreted as variable name by MATLAB.
Tan Do (VGU) Introduction to MATLAB Lecture 2 37 / 43
char arrays

Characters are stored in MATLAB using the so-called character


encoding.
In the character encoding, all characters are put in a sequence with
equivalent integer values.

Specically, MATLAB uses ASCII encoding (American Standard Code


for Information Interchange).

Standard ASCII has 128 characters with equivalent integers from 0 to


127.
The rst 32 characters are non-printable characters. Letters of the
alphabet are put in dictionary order.

Tan Do (VGU) Introduction to MATLAB Lecture 2 38 / 43


char arrays

Converting characters to equivalent integers

To convert a character, for example 'a', to its equivalent integer, type


» double(’a’)
ans =
97
which shows that 'a' is the 98th character in the character encoding.

The number type is not important, so it is also possible to type


» int32(’a’)
ans =
97

The function char reverses the process.


» char(97)
ans =
a

Tan Do (VGU) Introduction to MATLAB Lecture 2 39 / 43


char arrays

Note the dierence when MATLAB displays a number versus a character.


» var = 3
var =
3
» var = ’3’
var =
3

Tan Do (VGU) Introduction to MATLAB Lecture 2 40 / 43


char arrays

char arrays
Denition A sequence of characters is called a char array or a string.

Example 'America', 'New Zealand' are strings.

We can concatenate strings together.


s1 = ’New’; s2 = ’Zealand’;
s3 = [s1, ’ ’, s2]
s3 =
New Zealand

An empty string can be created by putting two single quotes together (with no spacing
in between).
s = ”;
c = class(s)
c =
char

Tan Do (VGU) Introduction to MATLAB Lecture 2 41 / 43


char arrays

To nd the equivalent integers of the characters in a string, type


» double(’America’)
ans =
65 109 101 114 105 99 97

MATLAB handles strings similarly to numeric arrays. So to get the


substring 'meri' of the string 'America', we can type
» s = ’America’;
» substr = s(2:5)
substr =
meri

Tan Do (VGU) Introduction to MATLAB Lecture 2 42 / 43


char arrays

sprintf function

A very useful function in MATLAB is sprintf.


The sprintf function writes new data to a preformatted string.

Example
» Intro = sprintf(’Hello! My name is %s.’, ’Tan’)
Intro =
Hello! My name is Tan.

» s = sprintf(’This %s class has roughly %d students.’, ’IT’, 50)


s =
This IT class has roughly 50 students.

» p = sprintf(’An approximation of %s is %f.’, ’pi’, 3.14)


p =

An approximation of pi is 3.14.

Tan Do (VGU) Introduction to MATLAB Lecture 2 43 / 43

You might also like