From cafa9c7112fe0c2e50b90acb6c210dfb40724f84 Mon Sep 17 00:00:00 2001 From: Patrick McNeal Date: Tue, 22 Apr 2014 14:24:02 -0400 Subject: [PATCH] Add initial solution with comments. --- cachematrix.R | 53 ++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 46 insertions(+), 7 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..19cb0c1707d 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,54 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## This function creates a special "matrix" object that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { + inverse <- NULL + # Set matrix value and delete cached inverse only if new matrix is + # different than current value + set <- function(y) { + if (!identical(x, y)) { + x <<- y + inverse <<- NULL + } + } + + # Return current matrix value + get <- function() x + + # Cache inverse value + setinverse <- function(solve) inverse <<- solve + + # Return cached inverse value + getinverse <- function() inverse + + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } -## Write a short comment describing this function +## 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 cacheSolve retrieves the inverse from the +## cache. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' -} + + # Return cached inverse value if one is found + inverse <- x$getinverse() + if(!is.null(inverse)) { + message("getting cached data") + return(inverse) + } + + # No cached inverse, so need to calculate + message("cached data not found, calculating value") + data <- x$get() + inverse <- solve(data, ...) + + # Cache inverse matrix for future use + x$setinverse(inverse) + + # Return inverse matrix + inverse +} \ No newline at end of file