Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update cachematrix.R #5750

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 43 additions & 10 deletions cachematrix.R
Original file line number Diff line number Diff line change
@@ -1,15 +1,48 @@
## Put comments here that give an overall description of what your
## functions do

## Write a short comment describing this function

# Function to create a special "matrix" object that can cache its inverse
makeCacheMatrix <- function(x = matrix()) {

inv <- NULL # Variable to store the cached inverse

# Function to set the matrix
set <- function(y) {
x <<- y
inv <<- NULL # Reset the cached inverse when the matrix changes
}

# Function to get the matrix
get <- function() x

# Function to set the inverse
setInverse <- function(inverse) inv <<- inverse

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

# Return a list of functions to interact with the cache
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}


## Write a short comment describing this function

# Function to compute the inverse of the matrix, caching the result
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getInverse() # Check if the inverse is already cached

# If cached inverse exists, return it
if (!is.null(inv)) {
message("Getting cached inverse")
return(inv)
}

# Otherwise, compute the inverse
mat <- x$get()
inv <- solve(mat, ...) # Compute inverse using solve()

x$setInverse(inv) # Cache the computed inverse
inv
}

# Example Usage
m <- matrix(c(2, 1, 3, 4), 2, 2) # Create a 2x2 invertible matrix
cachedMatrix <- makeCacheMatrix(m) # Create a cache matrix object
cacheSolve(cachedMatrix) # Compute and cache the inverse
cacheSolve(cachedMatrix) # Retrieve the cached inverse