From a6060d79182f24384e9ff2bbee6ea0557d7f3c34 Mon Sep 17 00:00:00 2001 From: Chris Holliday Date: Tue, 21 Oct 2014 22:41:55 -0400 Subject: [PATCH] first commit for caching --- cachematrix.R | 37 +++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..1f861192994 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,36 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## Methods to cache the inverse of a matrix and to obtain the cached version of +## said matrix +## on first call to obtain the matrix inverse, cache the inverse so all +## subsequent calls just return a copy makeCacheMatrix <- function(x = matrix()) { - + cached_inverse <- NULL + set <- function(y) { + x <<- y + cached_inverse <<- NULL + } + + get <- function() { x } + setinverse <- function(inverse) { cached_inverse <<- inverse } + getinverse <- function() { cached_inverse } + list(set=set, get=get, setinverse=setinverse, getinverse=getinverse) } -## Write a short comment describing this function +## method to return the inverse of a matrix, while ensureing that we cache +## the result cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' -} + inverse <- x$getinverse() + + if(!is.null(inverse)) { + message("getting cached data.") + return (inverse) + } + + data <- x$get() + inverse <- solve(data) + x$setinverse(inverse) + + inverse +} \ No newline at end of file