Module # 6 Doing math in R part 2 (R Programming)

 1. Consider A=matrix(c(2,0,1,3), ncol=2) and B=matrix(c(5,2,4,-1), ncol=2).

a) Find A + B 

A <- matrix(c(2, 0, 1, 3), ncol = 2)

B <- matrix(c(5, 2, 4, -1), ncol = 2)


result_addition <- A + B

print(result_addition)


     [,1] [,2]
[1,]    7    2
[2,]    5    2 


Description: A = [2 0, 1 3 ], B = [ 5 2, 4 -1 ]. Add both A + B = [ 2+5 , 0 +2 , 1 + 4 , 3+(-1) ] = [ 7 2 , 5 2 ] 


b) Find A - B

result_subtraction <- A - B
print(result_subtraction)

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

Description: A - B = [ 2 - 5, 0 - 2, 1 -4, 3 - (-1) ] = [ -3 -2, -3 4 ] 

2. Using the diag() function to build a matrix of size 4 with the following values in the diagonal 4, 1, 2, 

diagonal_values <- c(4, 1, 2, 3)
result_matrix <- diag(diagonal_values)
print(result_matrix)

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

Description: 
  • Using the diag() function, we create a diagonal matrix with specified values on the diagonal.
  • The resulting matrix has the specified values on the diagonal and zeros elsewhere


3. Generate the following matrix:

result_matrix <- diag(3, 5)
print(result_matrix)

     [,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

Description: 
  • Using the diag() function with the argument 3 and size 5, we generate a diagonal matrix with 3 on the diagonal.
  • The resulting matrix has 3 on the diagonal and zeros elsewhere.

Comments

Popular posts from this blog

Final Project [LIS4317]

Module # 8 Input/Output, string manipulation and plyr package

Module # 10 Building your own R package