Module # 6 Doing math in R part 2
Module # 6 Doing math in R part 2
1. Matrix Operations
Given two matrices:
A <- matrix(c(2, 0, 1, 3), ncol = 2)
B <- matrix(c(5, 2, 4, -1), ncol = 2)
a) Find A + B
To find the sum of matrices A and B, simply add corresponding elements:
A + B
Output:
[,1] [,2]
[1,] 7 2
[2,] 5 2
Explanation:
The sum of the matrices is calculated element by element:
(2 + 5) = 7
(0 + 2) = 2
(1 + 4) = 5
(3 + -1) = 2
b) Find A - B
To find the difference between matrices A and B, subtract corresponding elements:
A - B
Output:
[,1] [,2]
[1,] -3 -2
[2,] -3 4
Explanation:
The difference of the matrices is calculated element by element:
(2 - 5) = -3
(0 - 2) = -2
(1 - 4) = -3
(3 - -1) = 4
2. Creating a Diagonal Matrix
To build a 4x4 matrix with the diagonal values 4, 1, 2, and 3 using the diag() function.
diag(c(4, 1, 2, 3), nrow = 4)
Output:
[,1] [,2] [,3] [,4]
[1,] 4 0 0 0
[2,] 0 1 0 0
[3,] 0 0 2 0
[4,] 0 0 0 3
Explanation:
The diag() function is used to create a matrix with the specified values on the diagonal. In this case, the matrix is 4x4, and the numbers 4, 1, 2, and 3 are placed on the diagonal, with all other elements being zero.
3. Generate the Specified Matrix
To generate a 5x5 matrix where the first row starts with a 3 and is followed by four 1’s. The diagonal has values of 3, and the other values are 2. The structure should look like this:
matrix_data <- diag(3, 5)
matrix_data[1, 2:5] <- 1
matrix_data[2:5, 1] <- 2
matrix_data
Output:
[,1] [,2] [,3] [,4] [,5]
[1,] 3 1 1 1 1
[2,] 2 3 0 0 0
[3,] 2 0 3 0 0
[4,] 2 0 0 3 0
[5,] 2 0 0 0 3
Explanation:
By creating a 5x5 matrix with 3's along the diagonal using
diag(3, 5).Then, modify the matrix: The first row is updated with four 1’s starting from the second column, and the first column (from row 2 to 5) is filled with 2’s.
Comments
Post a Comment