diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..6f958c6d465 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,29 @@ -## Put comments here that give an overall description of what your -## functions do +## cachematrix: Functions to cache matrix inversion -## Write a short comment describing this function +## makeCacheMatrix sets up the scope for storing cache makeCacheMatrix <- function(x = matrix()) { - + m <- NULL # initialize cache to NULL + set <- function(y) { # changing value invalidates cache + x <<- y + m <<- NULL + } + get <- function() x # return original matrix + setinverse <- function(inverse) m <<- inverse # set cache value to supplied value + getinverse <- function() m + list(set = set, get = get, setinverse=setinverse, getinverse=getinverse) } - -## Write a short comment describing this function +## cacheSolve takes the list generated by makeCacheMatrix and either populates its cache +## or returns the cached value cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + m <- x$getinverse() # returns NULL if not yet cached + if (!is.null(m)) { + message('cached inverse') # report that returned value is from cache + return(m) + } + m <- solve(x$get()) # uses solve to get inverse of x + x$setinverse(m) + m }