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 #5740

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
43 changes: 35 additions & 8 deletions cachematrix.R
Original file line number Diff line number Diff line change
@@ -1,15 +1,42 @@
## Put comments here that give an overall description of what your
## functions do

## Write a short comment describing this function
# The following "makeCacheMatrix" function is to create a special "matrix" object that can cache its inverse

makeCacheMatrix <- function(x = matrix()) {

inv <- NULL # Initialize the inverse as NULL

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

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

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

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

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


## Write a short comment describing this function
# The following "cacheSolve" function is to compute the inverse of the "matrix" returned by makeCacheMatrix

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

if (!is.null(inv)) {
message("Getting cached inverse")
return(inv) # Return the cached inverse
}

# If inverse is not cached, calculate it
mat <- x$get()
inv <- solve(mat, ...) # Compute the inverse
x$setInverse(inv) # Cache the inverse
inv
}