1. Introduction
This R program demonstrates various operations on matrices, including creation, addition, subtraction, multiplication, and transposition. Matrices are fundamental structures in R for organizing and manipulating numerical data.
2. Program Steps
1. Create two matrices.
2. Perform addition of the two matrices.
3. Perform subtraction between the two matrices.
4. Perform multiplication of the two matrices.
5. Transpose the first matrix.
6. Print the results of these operations.
3. Code Program
# Step 1: Create two matrices
matrix1 <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2)
matrix2 <- matrix(c(5, 6, 7, 8), nrow = 2, ncol = 2)
# Step 2: Perform addition
addition_result <- matrix1 + matrix2
# Step 3: Perform subtraction
subtraction_result <- matrix1 - matrix2
# Step 4: Perform multiplication
multiplication_result <- matrix1 %*% matrix2
# Step 5: Transpose the first matrix
transpose_matrix1 <- t(matrix1)
# Step 6: Print the results
print("Addition of two matrices:")
print(addition_result)
print("Subtraction of two matrices:")
print(subtraction_result)
print("Multiplication of two matrices:")
print(multiplication_result)
print("Transpose of the first matrix:")
print(transpose_matrix1)
Output:
Addition of two matrices: [,1] [,2] [1,] 6 9 [2,] 8 11 Subtraction of two matrices: [,1] [,2] [1,] -4 -5 [2,] -6 -7 Multiplication of two matrices: [,1] [,2] [1,] 19 22 [2,] 43 50 Transpose of the first matrix: [,1] [,2] [1,] 1 3 [2,] 2 4
Explanation:
1. matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2) and matrix(c(5, 6, 7, 8), nrow = 2, ncol = 2): Create two 2x2 matrices.
2. matrix1 + matrix2: Adds the two matrices.
3. matrix1 - matrix2: Subtracts the second matrix from the first.
4. matrix1 %*% matrix2: Multiplies the two matrices.
5. t(matrix1): Transposes the first matrix.
6. print("Addition of two matrices:"), print(addition_result): Prints the result of matrix addition.
7. print("Subtraction of two matrices:"), print(subtraction_result): Prints the result of matrix subtraction.
8. print("Multiplication of two matrices:"), print(multiplication_result): Prints the result of matrix multiplication.
9. print("Transpose of the first matrix:"), print(transpose_matrix1): Prints the transpose of the first matrix.
Comments
Post a Comment