diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..e6fbac675bb 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,40 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## Matrix inversion is usually a costly computation, this module creates an API +## to cache the inverse of a matrix rather than compute it repeatedly +## makeCacheMatrix: This function creates a special "matrix" object that +## can cache its inverse. makeCacheMatrix <- function(x = matrix()) { + inv <- NULL -} + set <- function(y) { + x <<- y + inv <<- NULL + } + get <- function() x + setsolve <- function(solve) inv <<- solve + getsolve <- function() inv + + list(set = set, + get = get, + setsolve = setsolve, + getsolve = getsolve) +} -## Write a short comment describing this function +## cacheSolve: This function computes the inverse of the special "matrix" +## returned by makeCacheMatrix above. If the inverse has +## already been calculated (and the matrix has not changed), +## then the cachesolve should retrieve the inverse from the cache. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + inv <- x$getsolve() + if(!is.null(inv)) { + message("getting cached data") + return(inv) + } + data <- x$get() + inv <- solve(data) + x$setsolve(inv) + inv }