Matrix Operations and Diagonal Construction in R

# Question 1
# Define matrices A and B
A <- matrix(c(2,0,1,3), ncol=2)
B <- matrix(c(5,2,4,-1), ncol=2)

# a) A + B
A_plus_B <- A + B

# b) A - B
A_minus_B <- A - B

A
B
A_plus_B
A_minus_B

# Question 2
# Create diagonal matrix with values 4,1,2,3
D <- diag(c(4,1,2,3))
D

# Question 3
# Generate the required 5x5 matrix
M <- diag(3, 5)
M[2:5,1] <- 2
M[1,2:5] <- 1
M


 In this assignment, I practiced basic matrix operations in R, including matrix addition, subtraction, and constructing matrices using the diag() function. First, I defined matrices A and B using the matrix() function. I then computed A + B and A − B to demonstrate how R performs element-wise arithmetic operations on matrices of the same dimensions. This reinforces how R handles structured data efficiently using vectorized operations.

Next, I used the diag() function to construct a 4×4 diagonal matrix with the values 4, 1, 2, and 3 along the main diagonal. The diag() function is a concise way to create identity and diagonal matrices without manually entering each element, which aligns with the emphasis on writing efficient and readable code.

Finally, I generated a 5×5 matrix by combining the diag() function with indexing techniques. I started with a diagonal matrix multiplied by 3 and then modified specific rows and columns using matrix indexing. This approach demonstrates how matrices in R can be programmatically constructed and edited without manually typing every value.

These exercises connect directly to Norman (2011), The Art of R Programming, which highlights understanding how R structures data internally and how matrix operations are fundamental to many statistical computations. They also align with Wickham (2015), R Packages, particularly the discussion of clean, organized top-level code. By defining objects clearly and printing results in a structured way, the script remains readable, reproducible, and easy to test — key principles in writing professional R code.

Overall, this assignment strengthened my understanding of matrix manipulation, indexing, and writing clear, organized R scripts.

Comments

Popular posts from this blog

ABC vs. CBS: Comparing Fictional Presidential Poll Data in R

Assignment #10: Building Your Own R Package

Module # 4 Programming structure assignment