0% found this document useful (0 votes)
5 views29 pages

Chap 3 - BSD2223

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

CHAPTER 3: Matrices and Arrays

Data Science Programming II (BSD2223)

Assoc. Prof. Dr Roslinazairimah Zakaria


Centre for Mathematical Sciences
CONTENTS

3.1 Matrices
3.11 Matrix Operations
3.12 Function on Matrix
3.2 Arrays
3.21 Array Operations
3.22 Function on Arrays

1 / 28
Learning Objectives

At the end of the lesson, students should be able to


• create matrices
• apply basic operation on matrices
• use functions on matrices
• create arrays
• apply basic operation on arrays
• use functions on arrays

2 / 28
3.1 Matrices

• A matrix presents data in a two-dimensional rectangular or


square forms.

• All entries in the matrix should be of the same data type and
with the same row or column lengths.

• Matrix has dimension attributes, that is the length of row by


the length of column, row × column.

• The dimension of a matrix can be checked using dim(.)


function.

3 / 28
Creating Matrices

• Matrix syntax:
matrix(vector, nrow = r, ncol=c, byrow = FALSE)

• By default, byrow=FALSE indicates that the matrix will be


filled by columns first. Otherwise, byrow=TRUE means that
the matrix will be filled by rows.

• The position of each entry/ element in a matrix is determined


by the row and column number.

4 / 28
Example 3.1 - Creating Matrices

## create numeric matrix


m1 <- matrix(1:12, nrow= 3); m1
m2 <- matrix(1:12, nrow= 3, ncol=4); m2
m3 <- matrix(1:12, nrow= 3, byrow=TRUE); m3

## create string matrix


m4 <- matrix(c("a", "b","c","d","e","f"), nrow= 3); m4

## naming rows and columns of a matrix


m1 <- matrix(1:12, nrow= 3,
dimnames = list(c("A","B","C"), c("D","E","F","G")))
m1
rownames(m1)
colnames(m1)

5 / 28
Example 3.2 - Creating Matrices
(i) Create matrix using rbind(.) or cbind(.)
c1 <- 1:6
c2 <- 7:12
cbind(c1,c2) #column bind
rbind(c1,c2) #row bind

(ii) Create matrix using dim(.)


m5 <- 5:19
dim(m5) <- c(5,3) # 5 rows x 3 columns
m5

(iii) Special matrix - identity matrix


diag(5) ##create identity matrix of 5 by 5
m7 <- matrix(-10:10, nrow=5); m7
diag(m7) ##extract diagonal elements

6 / 28
Example 3.3 - Creating Matrices

# construct 3 by 2 matrix with labels


dt <- c(1,26,24,68,10,15)
rnames <- c("R1", "R2","R3")
cnames <- c("C1", "C2")
mt1 <- matrix(dt, nrow=3, ncol=2,
dimnames=list(rnames, cnames))
mt1

mt2 <- matrix(15:18, nrow = 2,


dimnames = list(c("P","Q"), c("A","B")))
mt2

# create identity matrix and extract diagonal element


diag(4)
diag(mt2)
diag(3,4)

7 / 28
3.1.1 Matrix Operation

• Basic mathematical operations on matrices based on


element-wise operation which are addition, subtraction,
multiplication and division.

• Matrix algebra on matrices are addition, subtraction, scalar


multiplication and matrix multiplication.

• For matrix multiplication, the number of columns and rows


must be conformable. That is, the number of columns of first
matrix must be equal to the number of rows of second matrix.

• Matrix A and B is conformable if matrix Am×n × Bn×y then


the new matrix dimension is m × y .

8 / 28
Matrix Operation

Let Am×n and Bp×q be matrices.

Function Description
A+B Addition, row m = p and column n = q
A−B Subtraction, row m = p and column n = q
k ∗A Scalar multiplication
A% ∗ %B Matrix multiplication, n = p
solve(A) Inverse of matrix A. Am×m (square matrix)
det(A) Determinant of matrix A, |A| (A square matrix)

9 / 28
Example 3.4 - Matrix Operation
A <- matrix(data = 1:16, nrow = 4, ncol = 4,
byrow = TRUE); A
B <- matrix(data = 16:31, nrow = 4, ncol = 4,
byrow = FALSE); B

A + B
A - B
A * B
A/B

# Matrix Algebra
5*A # scalar multiplication
A %*% B # matrix multiplication
t(A) # transpose a matrix
A %*% t(A)

10 / 28
Inverse Matrix

• If A is a matrix of n × n (square matrix), then A−1 is the


inverse of matrix A.

• Properties of inverse matrix:


(i) Inverse matrix exist for square matrix (n × n)
(ii) Inverse of a matrix can be formed if the determinant of
the matrix is not zero.
(iii) A matrix multiply by its inverse will give an identity (I )
matrix: A × A−1 = I

• For practical applications, the inverse of a matrix can be used


for determining regressions, simulating 3D space in computer
graphics and encrypting messages.

11 / 28
Example 3.5 Inverse Matrix - solve(.) function
# Create 3 different vectors.
a1 <- c(3, 2, 8)
a2 <- c(6, 3, 2)
a3 <- c(5, 2, 4)

# Bind the 3 matrices row-wise: rbind(.)


A <- rbind(a1, a2, a3)

# matrix will have an inverse if determinat is nonzero


det(A) ## determinant matrix A must not zero

# find inverse using the solve() function.


solve(A)

# check inverse property: A*A_1 =I_n


A%*%solve(A)

12 / 28
Example 3.6 Inverse Matrix - inv(.) function

# Find inverse of a matrix using inv(.) function


library(matlib) # install.packages("matlib")

# create 3 by 3 matrix
x <- sample(1:50,9)
B <- matrix(x,nrow=3); B

# matrix will have an inverse if determinat is nonzero


det(B) ## determinant matrix B must not zero

# find inverse using the inv() function.


inv(B)
# check inverse property
round(B%*%inv(B),2)

13 / 28
3.1.2 Function on Matrix
Matrix is a two dimensional data structure, row (m) and
column(n). Let Am×n be a matrix, then each cell in the matrix is
denoted by aij for i = 1, 2, . . . , m and j = 1, 2, . . . , n.

Function Description
a[i,j] an element of row i and column j
a[i, ] all elements in row i
a[ ,j] all elements in column j
dim(A) dimension of matrix A
dimnames(A) labels for rows and columns
t(A) transpose of matrix A
diag(A) extract diagonal elements of matrix A
diag(k) k scalar, creates k by k identity matrix
diag(k,dim) k scalar, creates k value on the diagonal ma-
trix and set the matrix dimension: dim

14 / 28
Adding and Deleting Matrix

• Matrices can be reassigned and deletion or addition of rows or


columns can be done as follows. Let A and B are matrices,
then

Delete row i : A[−i, ]


Delete column j : B[ , −j]
Add row j : rbind(A, B)
Add column j : cbind(A, B)

• Square brackets are used with positive or negative indexes

15 / 28
Example 3.7 - Subset and Delete Matrix

## Subset a matrix
m6 <- c(3, 5, -7, 18, 0, 0.5, 1, 9, 6)
dim(m6) <- c(3,3)
m6

m6[1:2,] #select row 1&2 and all columns


m6[c(1,3),2] #select row 1&3 and column 2
m6[c(1,3),c(1,2)] #select row 1&3 and column 1&2
m6[-1,] #select all except row 1

16 / 28
Example 3.8 - Subset and Delete Matrix
## Subset a matrix
m6 <- c(3, 5, -7, 18, 0, 0.5)
dim(m6) <- c(3,2)
m6

m6[c(1,3),2] #select row 1&3 and column 2


m6[c(1,3),c(1,2)] #select row 1&3 and column 1&2
m6[-1,] #select all except row 1

## Modify a matrix
m6 <- c(3, 5, -7, 18, 0, 0.5)
dim(m6) <- c(3,2)
m6
m6[2,2] <- 99 #replace cell(2,2) with 99
m6
m6[m6 < 10] <- 0 #replace all elements < 10 with 0
m6
17 / 28
Example 3.9 - Add or Delete Elements of a Matrix

set.seed(1481)
x <- sample(-20:20, 9, replace=TRUE)
m1 <- matrix(x, nrow=3)
m1
m1[,-3] ##delete 3rd column
m1[-1, 3:2] ##delete 1st row and rearrange row 2&3
m1[-2, -c(1,3)] ##delete 2nd row and column 1&3

m2 <- m1 ##rename the matrix


m2
m2[3,] <- 2:4 ##replace row 3 with 2,3,4
m2
m2[c(1,2),3] <- 999 ##replace row 1&2 and col 3 with 999
m2

18 / 28
Statistical Functions on Matrix

colSums(x, na.rm = FALSE , dims = 1)


rowSums(x, na.rm = FALSE , dims = 1)
colMeans(x, na.rm = FALSE , dims = 1)
rowMeans(x, na.rm = FALSE , dims = 1)

19 / 28
apply(.) Function

Calculation in a matrix (or an array) can be done using apply(.)


function.

• Syntax: apply(x, margin, fun) where


– x is the array
– margin is the data used by row =1 or column=2
– fun is the function to be applied to the elemnt in the array.

• fun can be the sum, mean or etc.

20 / 28
Example 3.10 - Statistical Functions

set.seed(1481)
x1 <- sample(-20:20, 9, replace=TRUE); x1
m1 <- matrix(x1, nrow=3); m1

set.seed(58)
x2 <- sample(seq(-10,10)/2, 9, replace=TRUE); x2
m3 <- matrix(x2, nrow=3); m3

m_com <- cbind(m1,m3); m_com


rowSums(m_com) # sum by each row
apply(m_com,1, sum)

rowMeans(m_com) # mean by each column


apply(m_com,1, mean)

21 / 28
3.2 Arrays

• Vector is 1-D, matrix is 2-D and arrays are general form of


vectors and matrices of dimension 3 or higher. Hence, it is
more complex data structures.

• In arrays, data is stored in the form of matrices, rows, and


columns. We can use the matrix level, row index, and column
index to access the matrix elements.

• Array fills the entries of each layer with the elements in a


strict column-wise form.

22 / 28
Array Syntax

Syntax: array(x, dim = (n, m, matrices, dimnames))


where
• x – input vector that is given to the array.

• n – number of row size in the array

• m – number of column size in the array

• matrices – number of matrices (layer) in the array

• dimnames – use to name the rows and columns.

23 / 28
Example 3.11 - Array (Create and Naming)

## create an array from 2 matrices of 3 by 3


v1 <- c(3,0,1)
v2 <- c(5,23,19,42,10,-5)
## create an array from 2 matrices of 3 by 3
ar1 <- array(c(v1,v2),dim = c(3,3,2)); ar1

## Name the matrix rows and columns


column.names <- c("COL1","COL2","COL3")
row.names <- c("ROW1","ROW2","ROW3")
matrix.names <- c("Matrix1","Matrix2")

ar2 <- array(c(v1,v2),dim = c(3,3,2),


dimnames = list(row.names,column.names,
matrix.names))
ar2

24 / 28
Example 3.12 - Array (Extract Element)

## Extract elements from the array


ar2[2,,2] ## element of row 2 of matrix 2
ar2[2,3,1] ## element of row 2, column 3 of matrix 1
ar2[,,2] ## matrix 2

25 / 28
Example 3.13 - Array (Algebraic Operation)
## Operation on Arrays
## Create 2 arrays
v3 <- 1:4
v4 <- c(1,5,11,10,6,12,-5,0,8,7,9,2)

ar3 <- array(c(v3,v4),dim = c(4,4,2)); ar3

v5 <- rep(2,8)
v6 <- seq(2,6, length=9)
ar4 <- array(c(v5,v6),dim = c(4,4,2)); ar4

## create matrix from array and sum the matrices


m1 <- ar3[,,1]
m2 <- ar4[,,1]

m1+m2
26 / 28
Example 3.14 - Array (Create from Matrix)

## Array
## Form a matrix of 3 by 4 for 2 layers
ar1 <- array(1:24, dim= c(3,4,2))
ar1

## Form an array
## Form a matrix of 3 by 4 for 2 layers and 2 sets
ar2 <- array(rep(1:24, times=3), dim= c(3,4,2,2))
ar2

## Form a matrix of 3 by 4 for 2 layers and 3 sets


ar3 <- array(rep(1:24, times=3), dim= c(3,4,2,3))
ar3

27 / 28
Example 3.15 - Array: apply(.) function
Syntax: apply(x, margin, fun)

## apply(.) Function
v5 <- rep(2,8)
v6 <- seq(2,6, length=8)
ar4 <- array(c(v5,v6),dim = c(4,4,2)); ar4

# fun = sum
apply(ar4, 1, sum) #c(1) sum through rows
apply(ar4, 2, sum) #c(2) sum through columns

# fun = mean
apply(ar4, 1, mean) #c(1) mean through rows
apply(ar4, 2, mean) #c(2) mean through columns

28 / 28

You might also like