Skip to content
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
34 changes: 34 additions & 0 deletions cachematrix.R
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,27 @@
## Write a short comment describing this function

makeCacheMatrix <- function(x = matrix()) {
inv <- NULL # Initialize the inverse to NULL

# Set the matrix and clear any previously cached inverse
set <- function(y) {
x <<- y
inv <<- NULL
}

# Get the matrix
get <- function() x

# Set the inverse of the matrix
setinverse <- function(inverse) inv <<- inverse

# Get the cached inverse
getinverse <- function() inv

# Return a list of the functions
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)

}

Expand All @@ -12,4 +33,17 @@ makeCacheMatrix <- function(x = matrix()) {

cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getinverse()

# If inverse is already cached, return it
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}

# Otherwise, compute the inverse
mat <- x$get()
inv <- solve(mat, ...) # Use solve to compute the inverse
x$setinverse(inv) # Cache the inverse
inv
}