Wednesday, September 25, 2024

BCA PART B 4.R program to calculate simple linear algebra operations

Program :

# Function for matrix addition
matrix_add <- function(A, B) {
  return(A + B)
}

# Function for matrix subtraction
matrix_subtract <- function(A, B) {
  return(A - B)
}

# Function for matrix multiplication
matrix_multiply <- function(A, B) {
  return(A %*% B)  # Matrix multiplication in R uses the %*% operator
}

# Function to calculate the determinant of a matrix
matrix_determinant <- function(A) {
  return(det(A))
}

# Function to calculate the inverse of a matrix
matrix_inverse <- function(A) {
  if (det(A) != 0) {
    return(solve(A))  # solve(A) gives the inverse in R
  } else {
    return("Matrix is singular, inverse does not exist.")
  }
}

# Function to calculate the dot product of two vectors
vector_dot_product <- function(v1, v2) {
  return(sum(v1 * v2))  # Element-wise multiplication and summing it up
}

# Example matrices and vectors
A <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2)  # 2x2 matrix
B <- matrix(c(5, 6, 7, 8), nrow = 2, ncol = 2)  # 2x2 matrix
v1 <- c(1, 2, 3)  # Vector 1
v2 <- c(4, 5, 6)  # Vector 2

# Performing operations
cat("Matrix A:\n")
print(A)
cat("\nMatrix B:\n")
print(B)

cat("\nMatrix Addition (A + B):\n")
print(matrix_add(A, B))

cat("\nMatrix Subtraction (A - B):\n")
print(matrix_subtract(A, B))

cat("\nMatrix Multiplication (A * B):\n")
print(matrix_multiply(A, B))

cat("\nDeterminant of Matrix A:\n")
print(matrix_determinant(A))

cat("\nInverse of Matrix A:\n")
print(matrix_inverse(A))

cat("\nDot Product of vectors v1 and v2:\n")

print(vector_dot_product(v1, v2)) 

Output :

Matrix A:

     [,1] [,2]

[1,]    1    3

[2,]    2    4


Matrix B:

     [,1] [,2]

[1,]    5    7

[2,]    6    8


Matrix Addition (A + B):

     [,1] [,2]

[1,]    6   10

[2,]    8   12


Matrix Subtraction (A - B):

     [,1] [,2]

[1,]   -4   -4

[2,]   -4   -4


Matrix Multiplication (A * B):

     [,1] [,2]

[1,]   23   31

[2,]   34   46


Determinant of Matrix A:

-2


Inverse of Matrix A:

     [,1] [,2]

[1,]   -2  1.5

[2,]    1 -0.5


Dot Product of vectors v1 and v2:

32

Explanation:

  1. Matrix Addition (matrix_add):

    • Adds two matrices element-wise.
  2. Matrix Subtraction (matrix_subtract):

    • Subtracts two matrices element-wise.
  3. Matrix Multiplication (matrix_multiply):

    • Performs matrix multiplication using the %*% operator in R.
  4. Determinant of a Matrix (matrix_determinant):

    • Computes the determinant of a matrix using the det() function.
  5. Inverse of a Matrix (matrix_inverse):

    • Uses the solve() function to calculate the inverse of a matrix. If the determinant is zero, the matrix is singular and doesn't have an inverse.
  6. Dot Product of Vectors (vector_dot_product):

    • Computes the dot product of two vectors using element-wise multiplication and then summing the results.


No comments:

Post a Comment