Module 6: Matrix Operations and Construction

GitHub Repository: r-programming-assignments/Assignment_06.R at main · AustinTCurtis/r-programming-assignments

Part I — Matrix Addition & Subtraction

In this section, I’m creating two matrices A and Busing the matrix() function. Both matrices have 2 columns. After defining them, I perform matrix addition (A+B) and matrix subtraction (A-B) These operations are performed elementwise, meaning R adds or subtracts each corresponding element from the same position in both matrices.

R Code:

# Define two 2x2 matrices A and B

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

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


# Display A and B

A

B


# Matrix addition

A_plus_B <- A + B

A_plus_B


# Matrix subtraction

A_minus_B <- A - B

A_minus_B


Part II — Creating a Diagonal Matrix

Here, I use the diag() function to create a 4×4 diagonal matrix called D. A diagonal matrix has non-zero values only along its main diagonal (from top left to bottom right), with zeros everywhere else. I specify the diagonal entries as the vector (4, 1, 2, 3)

R Code:

# Create a 4x4 diagonal matrix with diagonal entries 4, 1, 2, 3

D <- diag(c(4, 1, 2, 3))


# Display the diagonal matrix

D


Part III — Constructing a Custom 5×5 Matrix

In this part, I programmatically create a custom 5×5 matrix that matches a specific pattern. The diagonal elements are all 3, the first column contains 2's, and the first row contains 1's, (except for the top-left corner which is 3). I start by generating a diagonal matrix, then overwrite certain rows and columns to create the desired structure.

R Code:

# Step 1: Create a 5x5 diagonal matrix with all diagonal entries equal to 3

base <- diag(3, 5)


# Step 2: Fill the first column with 2s

base[, 1] <- 2


# Step 3: Fill the first row with 1s, except the [1,1] position (which should be 3)

base[1, ] <- 1

base[1, 1] <- 3


# Step 4: Display the final matrix

base

Comments

Popular posts from this blog

Module #4 Visualizing and Interpreting Hospital Patient Data

Module # 2 Assignment Importing Data and Function Evaluation in R