From 84661fcafa626bcb43973aefa1cd3d7293b53b06 Mon Sep 17 00:00:00 2001 From: Adam Sunderland Date: Sun, 20 Apr 2014 15:10:40 -0500 Subject: [PATCH 1/2] initial matrix inverse caching --- cachematrix.R | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..7771c043708 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,9 +1,25 @@ -## Put comments here that give an overall description of what your -## functions do +## These two functions allow a user to cache the inverse computation on +## a matrix. This is beneficial in that the inverse will not need to be +## recomputed for each iteration of a loop. -## Write a short comment describing this function +## In this function we create 4 methods that allow the user to get +## and set a cached matrix, as well get and set the value for the inverse +## of the matrix. +## makeCacheMatrix returns a list of these 4 functions so that a user +## can appropriately update the cached inverse. makeCacheMatrix <- function(x = matrix()) { + i <- NULL + set <- function(y) { + x <<- y + i <<- NULL + } + get <- function() x + setinverse <- function(inverse) i <<- inverse + getinverse <- function() i + list(set = set, get = get, + setmean = setmean, + getmean = getmean) } @@ -11,5 +27,13 @@ makeCacheMatrix <- function(x = matrix()) { ## Write a short comment describing this function cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + i <- x$getinverse() + if(!is.null(i)) { + message("getting cached inverse") + return(i) + } + data <- x$get() + i <- solve(data, ...) + x$setinverse(i) + i } From 492a0efab4cdd673e0d89f9268aa1b507a0644a7 Mon Sep 17 00:00:00 2001 From: Adam Sunderland Date: Sun, 20 Apr 2014 15:22:19 -0500 Subject: [PATCH 2/2] inverse caching working Improved documentation Fixed typos --- cachematrix.R | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index 7771c043708..c6d091a3573 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -17,21 +17,26 @@ makeCacheMatrix <- function(x = matrix()) { get <- function() x setinverse <- function(inverse) i <<- inverse getinverse <- function() i - list(set = set, get = get, - setmean = setmean, - getmean = getmean) + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } -## Write a short comment describing this function +## cacheSolve first checks if the inverse has been calculated and cached. +## If it was available it returns it immediately. If not, it calculates the +## inverse, caches it for future requests, and then returns the inverse. cacheSolve <- function(x, ...) { + #try to get inverse and return immediately if available i <- x$getinverse() if(!is.null(i)) { message("getting cached inverse") return(i) } + + #no cache was present, so calculate the inverse and cache it data <- x$get() i <- solve(data, ...) x$setinverse(i)