You are on page 1of 10

10/26/23, 10:53 AM Matrices

Matrices
AUTHOR
Dr. Mohammad Nasir Abdullah

Matrices

A matrix is a two-dimensional data structure where data is arranged in rows and columns. Each
element of a matrix can be referred to by its row and column number. Matrices are particularly useful
in linear algebra operations and statistical modeling.

Using the matrix function

The basic syntax for the matrix function is:

matrix(data, nrow, ncol, byrow, dimnames)

Arguments:

1. data : The actual data that will fill the matrix. It can be a vector of numbers, strings, or logical
values.
2. nrow : The number of rows the matrix should have.
3. ncol : The number of columns the matrix should have.
4. byrow : A logical value indicating whether the matrix should be filled by rows. If FALSE (the
default), the matrix is filled by columns.
5. dimnames : A list of two components giving the row and column names respectively.

Example 1 - based on number of rows


#creating a matrix with 3 rows
matrix(1:6, nrow = 3)

[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6

Example 2 - based on columns


#creating a matrix with 3 columns
matrix(1:6, ncol = 3)

[,1] [,2] [,3]


[1,] 1 3 5
[2,] 2 4 6

Example 3 - defined column and rows

https://sta334.s3.ap-southeast-1.amazonaw s.com/day3/Matrix+Array+Data+Frame.html 1/10


10/26/23, 10:53 AM Matrices

#creating 2 by 3 matrix
matrix(1:6, nrow=2, ncol=3)

[,1] [,2] [,3]


[1,] 1 3 5
[2,] 2 4 6

#creating 6 by 1 matrix
matrix(1:6, nrow=6, ncol=1)

[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6

#creating 1 by 6 matrix
matrix(1:6, nrow=1, ncol=6)

[,1] [,2] [,3] [,4] [,5] [,6]


[1,] 1 2 3 4 5 6

Example 4 - filled by rows


#create a matrix filled by columns (default behaviour)
matrix(1:6, nrow = 2)

[,1] [,2] [,3]


[1,] 1 3 5
[2,] 2 4 6

#create a matrix filled by rows


matrix(1:6, nrow=2, byrow=T)

[,1] [,2] [,3]


[1,] 1 2 3
[2,] 4 5 6

Example 5 - Dimensions Names


rownames <- c("Row1", "Row2")
colnames <- c("Col1", "Col2", "Col3")
matrix(1:6, nrow=2, ncol=3, dimnames=list(rownames, colnames))

Col1 Col2 Col3


Row1 1 3 5
Row2 2 4 6

https://sta334.s3.ap-southeast-1.amazonaw s.com/day3/Matrix+Array+Data+Frame.html 2/10


10/26/23, 10:53 AM Matrices

Matrices Arithmetic Operations

Addition

A <- matrix(c(1,2,3,4), nrow=2, ncol=2, byrow=TRUE)


B <- matrix(c(1,2,3,4), nrow=2, ncol=2)
A;B

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

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

A + B

[,1] [,2]
[1,] 2 5
[2,] 5 8

Subtraction

A - B

[,1] [,2]
[1,] 0 -1
[2,] 1 0

Matrix Multiplication

Element-wise multiplication

A * B

[,1] [,2]
[1,] 1 6
[2,] 6 16

Matrix multiplication

A %*% B

[,1] [,2]
[1,] 5 11
[2,] 11 25

Scalar Operations
https://sta334.s3.ap-southeast-1.amazonaw s.com/day3/Matrix+Array+Data+Frame.html 3/10
10/26/23, 10:53 AM Matrices

Multiplication

A * 2

[,1] [,2]
[1,] 2 4
[2,] 6 8

Division

A/2

[,1] [,2]
[1,] 0.5 1
[2,] 1.5 2

Transpose of a Matrix

t(A)

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

Matrix Inversion
If a matrix is invertible, you can find its inverse using the solve function.

To Inverse a matrix, it must be from square matrix and the determinant of a matrix must not be zero

#For this example, let's use a 2x2 invertible matrix


I <- matrix(c(4,7,2,6), nrow=2, ncol=2)
I

[,1] [,2]
[1,] 4 2
[2,] 7 6

#checking determinant
det(I)

[1] 10

#inverse matrix
solve(I)

[,1] [,2]
[1,] 0.6 -0.2
[2,] -0.7 0.4

https://sta334.s3.ap-southeast-1.amazonaw s.com/day3/Matrix+Array+Data+Frame.html 4/10


10/26/23, 10:53 AM Matrices

Diagonal of a Matrix

diag(A)

[1] 1 4

Matrix power
You can raise a matrix to a power using %^% operator from expm package

#first, install and load the package


library(expm)

Warning: package 'expm' was built under R version 4.2.2

Loading required package: Matrix

Warning: package 'Matrix' was built under R version 4.2.2

Attaching package: 'expm'

The following object is masked from 'package:Matrix':

expm

A %^% 2

[,1] [,2]
[1,] 7 10
[2,] 15 22

Matrix Indices

Accessing and manipulating the data within matrices often requires understanding matrix indexing,
which lets you retrieve or modify specific data points, rows, columns, or subsections of the matrix.

Basic indexing:
1) Single element access: To access a specific element in a matrix, you use the row and column index.

Syntax: matrix[row, column]

2) Row access: To access a specific row, specify the row index and leave the column index blank.

Syntax: matrix[row, ]

3) Column access: To access a specific column, leave the row index blank and specify the column
index.

Syntax: matrix[ , column]

https://sta334.s3.ap-southeast-1.amazonaw s.com/day3/Matrix+Array+Data+Frame.html 5/10


10/26/23, 10:53 AM Matrices

Advanced Indexing:
1) Multiple element access: You can access multiple elements by providing vectors for row and column
indices.

2) Conditional indexing: By using logical conditions, you can access elements that satisfy certain
criteria.

3) Negative indexing: If you provide negative indices, R will return all rows or column excluding those
indices.

Example:
Consider the following matrix:

M <- matrix(1:9, nrow=3, ncol=3)


M

[,1] [,2] [,3]


[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

1. Access the element in the 2nd row, 3rd column:

M[2,3]

[1] 8

2. Access the entire 1st row

M[1, ]

[1] 1 4 7

3. Access the entire 2nd column

M[ , 2]

[1] 4 5 6

4. Access multiple elements (eg: 1st and 3rd rows of the 2nd and 3rd columns

M[c(1,3), c(2,3)]

[,1] [,2]
[1,] 4 7
[2,] 6 9

5. Access elements greater than 6

https://sta334.s3.ap-southeast-1.amazonaw s.com/day3/Matrix+Array+Data+Frame.html 6/10


10/26/23, 10:53 AM Matrices

M[ M > 6]

[1] 7 8 9

6. Access all row except the 2nd row

M[ -2 , ]

[,1] [,2] [,3]


[1,] 1 4 7
[2,] 3 6 9

Exercise:

Exercise 1: Basic Matrix Creation

1. Create a matrix with numbers from 1 to 12, having 4 rows. Print the matrix.

2. Now, reshape the same data into a matrix with 3 columns. Print the result.

Exercise 2: Filling Order

1. Create a matrix with numbers from 1 to 6, having 2 rows, filled by columns. Print the matrix.

2. Create another matrix with the same data, but this time filled by rows. Print the matrix and
compare with the previous one.

Exercise 3: Naming Matrix Dimensions

1. Create a matrix with numbers from 1 to 9, having 3 rows.

2. Assign row names as “R1”, “R2”, and “R3”. Assign column names as “C1”, “C2”, and “C3”.

3. Print the matrix with row and column names.

Exercise 4: Accessing Matrix Elements

1. Consider the matrix:

mat <- matrix(1:9, nrow=3, dimnames=list(c("R1", "R2", "R3"), c("C1", "C2", "C3")))

a. Print the element in the second row and third column. b. Print the entire second row. c. Print the
entire first column.

Exercise 5: Matrix Operations

1. Create two matrices:

A <- matrix(1:4, nrow=2)


B <- matrix(5:8, nrow=2)

https://sta334.s3.ap-southeast-1.amazonaw s.com/day3/Matrix+Array+Data+Frame.html 7/10


10/26/23, 10:53 AM Matrices

a. Perform and print the matrix addition of A and B. b. Perform and print the matrix multiplication of A
and B.

Exercise 6: Advanced Matrix Creation

1. Create a diagonal matrix with the numbers 4, 5, and 6 on its diagonal. Print the matrix.

2. Check if the matrix from the previous step is symmetric. Print the result.

Exercise 7: Basic Matrix Operations

1. Create two 2x2 matrices: A=[24​35​] B=[13​24​]

[,1] [,2]
[1,] 2 3
[2,] 4 5

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

a. Perform and print matrix addition for A and B.

b. Perform and print matrix subtraction for A and B.

Exercise 8: Matrix Multiplication

1. Using the matrices A and B from Exercise 7:

a. Perform and print element-wise multiplication.

b. Perform and print matrix multiplication.

Exercise 9: Scalar Operations

1. For the matrix A from Exercise 7:

a. Multiply the matrix by the scalar value 3 and print the result.

b. Divide the matrix by the scalar value 2 and print the result.

Exercise 10: Transposition and Inversion

1. Using the matrix A from Exercise 7:

a. Find and print the transpose of matrix A.

b. Find and print the inverse of matrix A. (Ensure the matrix is invertible first)

Exercise 11: Diagonal and Power Operations

1. For the matrix A from Exercise 7:

a. Extract and print the diagonal of the matrix.

b. Raise the matrix to the power of 3 and print the result.


https://sta334.s3.ap-southeast-1.amazonaw s.com/day3/Matrix+Array+Data+Frame.html 8/10
10/26/23, 10:53 AM Matrices

Exercise 12: Advanced Operations

1. Create a matrix C

[,1] [,2] [,3]


[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9

a. Perform matrix multiplication of A and C. Is it possible? If not, explain why.

b. Extract the second row and third column of matrix C and print them.

Exercise 13: Basic Matrix Indexing

1. Create the following matrix:

Matrix M:

matrix(1:9, nrow=3,ncol=3)

[,1] [,2] [,3]


[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

a. Access and print the element in the 3rd row, 1st column.

b. Retrieve the entire 2nd row. What values do you get?

c. Extract the entire 3rd column. What values are present?

Exercise 14: Advanced Matrix Indexing

Using the matrix M from Exercise 13:

a. Access and print the elements in the 1st and 3rd rows of the 2nd column.

b. Extract a submatrix containing the 1st and 2nd rows of the 1st and 3rd columns.

c. Can you retrieve all elements of M that are greater than 4? If so, which elements satisfy this
condition?

Exercise 15: Conditional Indexing

Still with matrix M:

a. Identify and print elements that are even numbers.

b. Retrieve all elements that are less than 7 and are odd numbers.

Exercise 16: Negative Indexing

Once again, with matrix M:

https://sta334.s3.ap-southeast-1.amazonaw s.com/day3/Matrix+Array+Data+Frame.html 9/10


10/26/23, 10:53 AM Matrices

a. Access and print the matrix excluding the 2nd row.

b. Extract the matrix without the 1st and 3rd columns.

Exercise 17: Practical Application

Imagine matrix M represents scores of 3 students in 3 subjects. Rows represent students and columns
represent subjects.

a. If the 3rd subject is “Math”, extract scores of all students in Math.

b. The second student retook the exam for the 1st subject and scored a 5. Update the matrix to reflect
this score.

c. Calculate the average score for the 1st student across all subjects.

https://sta334.s3.ap-southeast-1.amazonaw s.com/day3/Matrix+Array+Data+Frame.html 10/10

You might also like