diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..b103d0f4918 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,39 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function - +## Make a cached 'matrix' with an initially unset inverse makeCacheMatrix <- function(x = matrix()) { - + # Inverse is initially null + i <- NULL + set <- function(y) { + # Set the data and the inverse into the parent scope + x <<- y + i <<- NULL + } + # Get the value of the matrix + get <- function() x + # Set the *cached* inverse of the matrix + setinv <- function(inv) i <<- inv + # Get the *cached* inverse of the matrix + getinv <- function() i + # Return a named-list with the data and functions embedded in it + list(set = set, get = get, + setinv = setinv, + getinv = getinv) } - -## Write a short comment describing this function - +## Memoize the solve function so as to provide a cached version of the inverse, if available, otherwise +## calculate, cache and return the inverse. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + # Get the inverse, if the inverse is already calculated return it + i <- x$getinv() + if (!is.null(i)) { + message("getting cached data") + return(i) + } + # Retrieve the data from the 'matrix' + data <- x$get() + # Solve the matrix to retrieve the inverse, passing the additional options from the caller + i <- solve(data, ...) + # Store the result + x$setinv(i) + i } +