Tuesday, May 23, 2023

1 Function to create a matrix object with caching capabilities makeCacheMatrix <- function(matrix = numeric()) { inverse <- NULL

# Function to set the matrix set <- function(matrix_input) { matrix <<- matrix_input inverse <<- NULL # Reset the cached inverse when the matrix is updated }

# Function to get the matrix get <- function() { matrix }

# Function to set the cached inverse setInverse <- function(inverse_matrix) { inverse <<- inverse_matrix }

# Function to get the cached inverse getInverse <- function() { inverse }

# Return a list of functions list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) }

2 Function to compute the inverse of a matrix with caching cacheSolve <- function(cacheMatrix) { # Check if the cached inverse exists if (!is.null(cacheMatrixgetInverse())){  message("Getting cachedinverse")  return(cacheMatrixgetInverse()) }

# If the cached inverse doesn’t exist, calculate the inverse matrix_data <- cacheMatrix$get() inverse_matrix <- solve(matrix_data)

# Cache the inverse cacheMatrix$setInverse(inverse_matrix)

inverse_matrix }

Create a matrix

matrix_data <- matrix(c(1, 2, 3, 4), nrow = 2)

3 Create a cache matrix object

cacheMatrix <- makeCacheMatrix(matrix_data)

4 Compute the inverse using cacheSolve

inverse_matrix <- cacheSolve(cacheMatrix)

Cached Inverse Matrix:
Column 1Column 2
Row 1-21.5
Row 21-0.5
Create Matrix

1 Function to create a matrix object with caching capabilities makeCacheMatrix <- function(matrix = numeric()) { inverse <- NULL

# Function to set the matrix set <- function(matrix_input) { matrix <<- matrix_input inverse <<- NULL # Reset the cached inverse when the matrix is updated }

# Function to get the matrix get <- function() { matrix }

# Function to set the cached inverse setInverse <- function(inverse_matrix) { inverse <<- inverse_matrix }

# Function to get the cached inverse getInverse <- function() { inverse }

# Return a list of functions list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) }

2 Function to compute the inverse of a matrix with caching cacheSolve <- function(cacheMatrix) { # Check if the cached inverse exists if (!is.null(cacheMatrix\(getInverse())) { message("Getting cached inverse") return(cacheMatrix\)getInverse()) }

# If the cached inverse doesn’t exist, calculate the inverse matrix_data <- cacheMatrix$get() inverse_matrix <- solve(matrix_data)

# Cache the inverse cacheMatrix$setInverse(inverse_matrix)

inverse_matrix }

Create a matrix

matrix_data <- matrix(c(1, 2, 3, 4), nrow = 2)

3 Create a cache matrix object

cacheMatrix <- makeCacheMatrix(matrix_data)

4 Compute the inverse using cacheSolve

inverse_matrix <- cacheSolve(cacheMatrix)

Pages