Matrix Introduction: IIT Guwahati
Matrix Introduction: IIT Guwahati
IIT Guwahati
1/4
Vectors and Matrices
I In the previous module, we have learnt about vectors. An array is a
multi-dimensional extension of a vector. As a special case, if the
array has only two dimension, then such an array is also called a
matrix.
2/4
Vectors and Matrices
I In the previous module, we have learnt about vectors. An array is a
multi-dimensional extension of a vector. As a special case, if the
array has only two dimension, then such an array is also called a
matrix.
2/4
Arrays and Matrices
3/4
Arrays and Matrices
3/4
Arrays and Matrices
3/4
Matrices in R
4/4
Matrices in R
4/4
Creating Matrices
IIT Guwahati
1/7
Creating an arbitrary Matrix
I Any arbitrary matrix can be created in R using matrix() function as:-
matrix(seq(1,20,by = 1),nrow = 2,ncol = 10, byrow = TRUE)
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,] 1 2 3 4 5 6 7 8 9 10
## [2,] 11 12 13 14 15 16 17 18 19 20
2/7
Creating an arbitrary Matrix
I Any arbitrary matrix can be created in R using matrix() function as:-
matrix(seq(1,20,by = 1),nrow = 2,ncol = 10, byrow = TRUE)
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,] 1 2 3 4 5 6 7 8 9 10
## [2,] 11 12 13 14 15 16 17 18 19 20
I Here the arguments nrow and ncol indicates the desired number of
rows and columns in the matrix respectively; whereas the argument
byrow is a logical argument, indicating whether or not to fill up the
matrix by row.
2/7
Creating an arbitrary Matrix
I Any arbitrary matrix can be created in R using matrix() function as:-
matrix(seq(1,20,by = 1),nrow = 2,ncol = 10, byrow = TRUE)
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,] 1 2 3 4 5 6 7 8 9 10
## [2,] 11 12 13 14 15 16 17 18 19 20
I Here the arguments nrow and ncol indicates the desired number of
rows and columns in the matrix respectively; whereas the argument
byrow is a logical argument, indicating whether or not to fill up the
matrix by row.
I We can also create a matrix of constant value as:
## [,1] [,2] [,3]
## [1,] 99 99 99
## [2,] 99 99 99
2/7
Operations on Matrices in R
## [1] 2 3
3/7
Operations on Matrices in R
## [1] 2 3
I We can also get the number of rows and columns in a matrix using
nrow() and ncol() functions respectively. We can also find out the
total number of elements in a matrix usiong length() function as:
l = length(mat)
l
## [1] 6
3/7
More operations on Matrices in R
## [1] 99 99 99 99 99 99
4/7
More operations on Matrices in R
## [1] 99 99 99 99 99 99
I The length of the above vector will be same as the length of the matrix
and we can find it using the length() function. We can get our
original matrix from the vector as:
mat1 = matrix(data = vec,nrow = 2,ncol = 3)
mat1
4/7
Type of data matrix in R
I Like vectors, matrices contain data of one type. We can create
numeric, integer, character, and logical matrices by adding the
corresponding values in the data argument while creating a matrix.
5/7
Type of data matrix in R
I Like vectors, matrices contain data of one type. We can create
numeric, integer, character, and logical matrices by adding the
corresponding values in the data argument while creating a matrix.
matrix(seq(0, 4.5, length.out = 9), nrow = 3)#numeric matrix
5/7
Filling up elements in a matrix by row
I Suppose we create a matrix by filling up elements rowwise as:
matrix(data = 1:9, nrow = 3, byrow = TRUE)
6/7
Filling up elements in a matrix by row
I Suppose we create a matrix by filling up elements rowwise as:
matrix(data = 1:9, nrow = 3, byrow = TRUE)
7/7
Filling up elements in a matrix by column
I Suppose we create a matrix by filling up elements rowwise as:
matrix(data = 1:9, nrow = 3, byrow = FALSE)
IIT Guwahati
1/3
Some Functions for Matrices
2/3
More Functions for Matrices
I The following functions are some useful functions for matrices:
3/3
Mathematical Operations
IIT Guwahati
1/5
Matrices and Scalars
I Matrices are often used for arithmetic operations to solve mathematical
problems like solving system of linear equations and several others. All
mathematical operations, applied to vectors, can also be
applied to matrices.
2/5
Matrices and Scalars
I Matrices are often used for arithmetic operations to solve mathematical
problems like solving system of linear equations and several others. All
mathematical operations, applied to vectors, can also be
applied to matrices.
I One of the simplest operations is to work with a matrix and a scalar in
the following manner:
x = matrix(1:4,nrow = 2)
x+2 #adding 2 to a matrix
## [,1] [,2]
## [1,] 3 5
## [2,] 4 6
x*3 #multiplying 3 to a matrix
## [,1] [,2]
## [1,] 3 9
## [2,] 6 12
2/5
Matrices and Vectors
I We can also perform arithmetic operations using a matrix and a vector.
For example, we consider a 2 × 2 matrix and multiply it with a vector
of length 2 to get their product as:
x = matrix(1:4,nrow = 2)
y = c(5,20)
x*y
## [,1] [,2]
## [1,] 5 15
## [2,] 40 80
3/5
Matrices and Vectors
I We can also perform arithmetic operations using a matrix and a vector.
For example, we consider a 2 × 2 matrix and multiply it with a vector
of length 2 to get their product as:
x = matrix(1:4,nrow = 2)
y = c(5,20)
x*y
## [,1] [,2]
## [1,] 5 15
## [2,] 40 80
I We can compute the above product in another way as:
z = matrix(y,nrow = 2,ncol = 2)
x*z
## [,1] [,2]
## [1,] 5 15
## [2,] 40 80
3/5
Matrices and Matrices
## [,1] [,2]
## [1,] 11 33
## [2,] 22 44
x/y
## [,1] [,2]
## [1,] 0.1 0.1
## [2,] 0.1 0.1
4/5
Other Mathematical Operations on Matrices
I Other than simple arithmetic operations, R comes with a wide range of
functions for mathematical tasks that are performed on Matrices, some
of which are as follows:
5/5
Matrix Attributes
IIT Guwahati
1/7
Checking attributes of a matrix
2/7
Checking attributes of a matrix
2/7
Checking attributes of a matrix
## $dim
## [1] 2 10
2/7
Dimension
I Any matrix has the dimension attribute which can be computed using
dim(), nrow() and ncol() functions.
3/7
Dimension
I Any matrix has the dimension attribute which can be computed using
dim(), nrow() and ncol() functions.
I For any matrix, the function dim() returns an integer vector of
length 2 where the first element represents number of rows and
second one represents number of columns in that matrix.
3/7
Dimension
I Any matrix has the dimension attribute which can be computed using
dim(), nrow() and ncol() functions.
I For any matrix, the function dim() returns an integer vector of
length 2 where the first element represents number of rows and
second one represents number of columns in that matrix.
dim(x)
## [1] 2 10
c("no. of rows" = nrow(x), "no. of columns" = ncol(x))
3/7
Length and Type of Matrix
I The length of a matrix is simply the total number of elements of the
matrix, or the length of the underlying atomic vector.It can be found
using length() function.
4/7
Length and Type of Matrix
I The length of a matrix is simply the total number of elements of the
matrix, or the length of the underlying atomic vector.It can be found
using length() function.
I Similar to vectors, type of data in a matrix can be determined by
functions class() and typeof() which tells us the type of the data
present in the matrix or whether the matrix is of class matrix or array.
4/7
Length and Type of Matrix
I The length of a matrix is simply the total number of elements of the
matrix, or the length of the underlying atomic vector.It can be found
using length() function.
I Similar to vectors, type of data in a matrix can be determined by
functions class() and typeof() which tells us the type of the data
present in the matrix or whether the matrix is of class matrix or array.
x <- matrix(c(1L, 2L, 3L, 4L), ncol = 2)
length(x)
## [1] 4
class(x)
## [1] "integer"
4/7
Dimension Names
I The function names(), which works for vectors, no longer works for
matrices as they are two-dimensional.
5/7
Dimension Names
I The function names(), which works for vectors, no longer works for
matrices as they are two-dimensional.
I For matrices, we have rownames() indicating names of rows in a
matrix, colnames() indicating names of columns in a matrix and
dimnames() indicating all the dimension names.
x <- matrix(data = 1:9, nrow = 3, ncol = 3)
rownames(x)
## NULL
5/7
Dimension Names
I The function names(), which works for vectors, no longer works for
matrices as they are two-dimensional.
I For matrices, we have rownames() indicating names of rows in a
matrix, colnames() indicating names of columns in a matrix and
dimnames() indicating all the dimension names.
x <- matrix(data = 1:9, nrow = 3, ncol = 3)
rownames(x)
## NULL
rownames(x) <- c("Row 1", "Row 2", "Row 3")
colnames(x) <- c("Col A", "Col B", "Col C")
x
6/7
Changing Dimension Names
I At any point of time, we can use rownames() and colnames() to
change the existing names in a matrix as:
colnames(x) <- c("first","second","third")
x
7/7
Creating Named Matrices
I We can directly create named matrices using the matrix() function as:
x <- matrix(data = 1:9, nrow = 3, ncol = 3,
dimnames = list(c("Row_1", "Row_2", "Row_3"),
c("Col_A", "Col_B", "Col_C")))
x
7/7
Combine Objects
IIT Guwahati
1/5
Multiple Vectors
I A possible way of creating matrices in R is by combining two or more
vectors rowwise or columnwise as:
x <- c( 5, 5, 5)
y <- c(11, 22, 33)
z <- cbind(x,y) #combining columnwise
z
## x y
## [1,] 5 11
## [2,] 5 22
## [3,] 5 33
2/5
Multiple Vectors
I A possible way of creating matrices in R is by combining two or more
vectors rowwise or columnwise as:
x <- c( 5, 5, 5)
y <- c(11, 22, 33)
z <- cbind(x,y) #combining columnwise
z
## x y
## [1,] 5 11
## [2,] 5 22
## [3,] 5 33
u = rbind(x,y) #combining columnwise
u
3/5
Dimension Names While Combining Vectors
I R automatically assigns dimension names while using cbind() or
rbind() as:
par_age <- c(24, 25, 21)
par_height <- c(1.73, 1.62, 1.72)
par = rbind(age = par_age,height = par_height)
par
## age height
## [1,] 24 1.73
## [2,] 25 1.62
## [3,] 21 1.72
3/5
Multiple Matrices
I We can also create a matrix in R by combining two matrices rowwise or
columnwise as:
x1 <- matrix(1:2,ncol = 1,
dimnames =list(c("R_1", "R_2"),c("A")))
x2 <- matrix(101:102, ncol = 1,
dimnames = list(c("R_1", "R_2"),c("A")))
cbind(x1,x2) #combining columnwise
## A A
## R_1 1 101
## R_2 2 102
4/5
Multiple Matrices
I We can also create a matrix in R by combining two matrices rowwise or
columnwise as:
x1 <- matrix(1:2,ncol = 1,
dimnames =list(c("R_1", "R_2"),c("A")))
x2 <- matrix(101:102, ncol = 1,
dimnames = list(c("R_1", "R_2"),c("A")))
cbind(x1,x2) #combining columnwise
## A A
## R_1 1 101
## R_2 2 102
rbind(x1,x2) #combining rowwise
## A
## R_1 1
## R_2 2
## R_1 101
## R_2 102
4/5
Matrices and Vectors
I We can also create a matrix in R by combining vectors and matrices as:
x <- matrix(1:6, nrow = 3)
y <- c(900, 800,600)
cbind(x,y)
## y
## [1,] 1 4 900
## [2,] 2 5 800
## [3,] 3 6 600
5/5
Matrices and Vectors
I We can also create a matrix in R by combining vectors and matrices as:
x <- matrix(1:6, nrow = 3)
y <- c(900, 800,600)
cbind(x,y)
## y
## [1,] 1 4 900
## [2,] 2 5 800
## [3,] 3 6 600
options(width = 30)
w = rbind(x,y) # It will provide an error.
5/5
Subsetting Matrices
IIT Guwahati
1 / 14
Schematic Representation of a Matrix
I The schematic representation of a matrix can be seen in the figure
below:
2 / 14
Schematic Representation of a Matrix
I The schematic representation of a matrix can be seen in the figure
below:
2 / 14
Subsetting by index through the extraction of single element
I For matrices, we can access elements in a specific row and column in a
way similar to vectors, except that we have to specify the rows and the
columns as:
x[3,1]
3 / 14
Subsetting by index through the extraction of single element
I For matrices, we can access elements in a specific row and column in a
way similar to vectors, except that we have to specify the rows and the
columns as:
x[3,1]
3 / 14
Subsetting by index through extraction of multiple elements
I Like vectors, we can extract multiple elements from any matrix at the
same time.We can extract multiple rows for a specific column and vice
versa as:
mat = matrix(101:112,nrow = 4,ncol = 3)
mat[c(4,2),2] #Vector subsetting
4 / 14
Subsetting by index through extraction of multiple elements
I Like vectors, we can extract multiple elements from any matrix at the
same time.We can extract multiple rows for a specific column and vice
versa as:
mat = matrix(101:112,nrow = 4,ncol = 3)
mat[c(4,2),2] #Vector subsetting
## [,1] [,2]
## [1,] 102 106
## [2,] 103 107
4 / 14
Subsetting by index through extraction of rows or columns
I We can extract an entire row or column rather than extracting a single
element:
mat[1,] #Returns entire 1st row
5 / 14
Subsetting by index through extraction of rows or columns
I We can extract an entire row or column rather than extracting a single
element:
mat[1,] #Returns entire 1st row
## [,1] [,2]
## [1,] 105 109
5 / 14
Subsetting by name through the extraction of single element
## [1] 2
medals["Canada", "G"] #Subsetting by name
## [1] 2
6 / 14
Subsetting by name through extraction of rows or columns
I We can extract an entire row or column by names but the output will
be a named vector. The output will be a matrix only when we specify
drop = FALSE while extracting rows or columns as:
medals["Canada", ] #Output is a named vector
## G S B
## 2 1 1
medals["Canada", , drop = FALSE] #Output is a matrix
## G S B
## Canada 2 1 1
7 / 14
Subsetting by name through extraction of rows or columns
I We can extract an entire row or column by names but the output will
be a named vector. The output will be a matrix only when we specify
drop = FALSE while extracting rows or columns as:
medals["Canada", ] #Output is a named vector
## G S B
## 2 1 1
medals["Canada", , drop = FALSE] #Output is a matrix
## G S B
## Canada 2 1 1
I We can use further processing of above matrix to extract second
element:
medals["Canada", , drop = FALSE][2]
## [1] 1
7 / 14
Subsetting by logical vectors
I We can use logical vectors for subsetting a matrix in the following
manner:
id = medals[, "G"] > 2 #Logical vector
medals[id,] # Subsetting matrix by logical vector
## G S B
## USA 3 4 1
## England 3 1 5
8 / 14
Subsetting by logical vectors
I We can use logical vectors for subsetting a matrix in the following
manner:
id = medals[, "G"] > 2 #Logical vector
medals[id,] # Subsetting matrix by logical vector
## G S B
## USA 3 4 1
## England 3 1 5
I We can perform subsetting by logical vectors working in combination
with vector subsetting as:
which(medals>3,arr.ind = TRUE)
## row col
## USA 1 2
## England 2 3
8 / 14
Replacing elements in a matrix
I A nice practical application for subsetting with logical vectors is search
and replace where we can search all the elements that are needed to
be replaced and then replace them as:
x <- round(matrix(runif(10), nrow = 5,ncol = 2),1)
x[x>0.5] #Searching elements greater than 0.5
9 / 14
Replacing elements in a matrix
I A nice practical application for subsetting with logical vectors is search
and replace where we can search all the elements that are needed to
be replaced and then replace them as:
x <- round(matrix(runif(10), nrow = 5,ncol = 2),1)
x[x>0.5] #Searching elements greater than 0.5
## [,1] [,2]
## [1,] 0.5 0.5
## [2,] 0.5 0.5
## [3,] 0.5 0.5
## [4,] 0.0 0.3
## [5,] 0.5 0.3
9 / 14
Mixed Subsetting
10 / 14
Mixed Subsetting
## [1] 2
10 / 14
Mixed Subsetting
## [1] 2
id <- medals[, "G"] > 1
medals[id,"S"] #Subsetting by logical vector
10 / 14
Out of range Indexes
11 / 14
Out of range Indexes
11 / 14
Out of range Indexes
11 / 14
Summary of Subsetting Matrices
12 / 14
Sorting a Matrix
I Similar to vectors, we can perform sorting on a matrix using the
command sort().But we can only sort a specific column or row of the
matrix using sort() in the following manner:
stud <- matrix(c(24, 30, 24, 1.67, 1.93, 1.71, 5, 3, 2),
nrow = 3,dimnames = list(c("B","E","C"),
c("age","height","year")))
sort(stud[,"age"]) #increasing order sorting
## B C E
## 24 24 30
13 / 14
Sorting a Matrix
I Similar to vectors, we can perform sorting on a matrix using the
command sort().But we can only sort a specific column or row of the
matrix using sort() in the following manner:
stud <- matrix(c(24, 30, 24, 1.67, 1.93, 1.71, 5, 3, 2),
nrow = 3,dimnames = list(c("B","E","C"),
c("age","height","year")))
sort(stud[,"age"]) #increasing order sorting
## B C E
## 24 24 30
#decreasing order sorting
sort(stud[,"year"],decreasing = TRUE)
## B E C
## 5 3 2
13 / 14
Re-Ordering a Matrix
I For re-ordering any matrix, we use the function order() which returns
the position of the elements in the matrix from smallest to largest or
vice versa.
14 / 14
Re-Ordering a Matrix
I For re-ordering any matrix, we use the function order() which returns
the position of the elements in the matrix from smallest to largest or
vice versa.
correct_order <- order(stud[,"year"]) #Re-Ordering
correct_order
## [1] 3 2 1
14 / 14
Re-Ordering a Matrix
I For re-ordering any matrix, we use the function order() which returns
the position of the elements in the matrix from smallest to largest or
vice versa.
correct_order <- order(stud[,"year"]) #Re-Ordering
correct_order
## [1] 3 2 1
stud[correct_order,] # Re-ordered matrix
14 / 14
Plotting Matrices
IIT Guwahati
1/9
Plotting Functions For Matrices
I There are several functions for plotting matrices, some of which are
given below:
2/9
Plotting Functions For Matrices
I There are several functions for plotting matrices, some of which are
given below:
2/9
Generic X-Y plot of Matrix
I Using plot() function, R can plot any two columns of a matrix (if not
stated then first two) against each other ;thereby creating a 2d
scatter plot as:
3/9
Generic X-Y plot of Matrix
I Using plot() function, R can plot any two columns of a matrix (if not
stated then first two) against each other ;thereby creating a 2d
scatter plot as:
x <- seq(0, 2 * pi, length.out = 200)
m <- cbind("sft: 0" = sin(x),"sft: pi" = sin(x + pi))
plot(m,main = "Generic X-Y Plot")
Generic X−Y Plot
1.0
0.5
sft: pi
0.0
−0.5
−1.0
sft: 0
3/9
Matrix Plot
I Using matplot() function, R can plot data matrix columnwise where
each column gets a different colour and line type(or symbol if type =
“p” as default) as:
4/9
Matrix Plot
I Using matplot() function, R can plot data matrix columnwise where
each column gets a different colour and line type(or symbol if type =
“p” as default) as:
matplot(m,type = "l",main = "Matrix Plot")
Matrix Plot
1.0
0.5
0.0
m
−0.5
−1.0
4/9
Customized Matrix Plot
I We can customize our matrix plot as:
5/9
Customized Matrix Plot
I We can customize our matrix plot as:
matplot(x, m,type = "l",xlab = NA,
main = "Customized Matrix Plot")
legend("topleft",legend = colnames(m),col = 1:2,lty = 1:2)
axis(side = 1,at = c(0, pi, 2 * pi),line = 1,lwd = 0,
c(expression(0), expression(pi), expression(2 * pi)),
col = "steelblue") #Adding custom second axis
Customized Matrix Plot
1.0
sft: 0
sft: pi
0.5
0.0
m
−0.5
−1.0
0 1 2 3 4 5 6
0 π 2π 5/9
Image Plot
I For two dimensional data, we can plot them using image()
function.Let us consider a R dataset volcano to get an image plot as:
6/9
Image Plot
I For two dimensional data, we can plot them using image()
function.Let us consider a R dataset volcano to get an image plot as:
data("volcano")
class(volcano)
## [1] 87 61
image(volcano,main = "Image Plot")
Image Plot
1.0
0.8
0.6
0.4
0.2
0.0
6/9
Customized Image Plot
I We can also customize our image plot by changing the value of axes
and labelling them as:
7/9
Customized Image Plot
I We can also customize our image plot by changing the value of axes
and labelling them as:
image(x = 1:nrow(volcano),
y = 1:ncol(volcano),
z = volcano,
col = hcl.colors(100, "terrain"))
60
50
40
1:ncol(volcano)
30
20
10
20 40 60 80
1:nrow(volcano)
7/9
Contour Plot
I We can plot a series of contours in R using contour() function,which
works similar to image plot, as:
8/9
Contour Plot
I We can plot a series of contours in R using contour() function,which
works similar to image plot, as:
contour(volcano,main = "Contour Plot")
Contour Plot
1.0
110
110 120
100
0.8
170
160
0.6
130
150 150
180
170
0.4
190
180 160
140
0.2
10
0
110
100
110
0.0
8/9
Filled Contour Plot
I The filled contour plot does the same as contour plot but fills the area
between two contours instead of drawing them as lines in the following
manner:
9/9
Filled Contour Plot
I The filled contour plot does the same as contour plot but fills the area
between two contours instead of drawing them as lines in the following
manner:
filled.contour(volcano,main = "Filled Contour Plot")
Filled Contour Plot
1.0
180
0.8
160
0.6
140
0.4
120
0.2
100
0.0
0.0 0.2 0.4 0.6 0.8 1.0
9/9