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(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)
5 Print the inverse matrix
print(inverse_matrix)
Column 1 | Column 2 | |
---|---|---|
Row 1 | -2 | 1.5 |
Row 2 | 1 | -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)
5 Print the inverse matrix
print(inverse_matrix)