From d6db7bb9741dc28d2d5727c629045dea8ca9e96d Mon Sep 17 00:00:00 2001 From: James Sanders Date: Wed, 21 May 2014 18:16:04 -0600 Subject: [PATCH] Implement `makeCacheMatrix` and `cacheSolve` --- cachematrix.R | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..34d6f5009dd 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,34 @@ -## Put comments here that give an overall description of what your -## functions do +## Gives the inverse of a given matrix, caching the result +## and using the cached result if available -## Write a short comment describing this function +## Builds an object that can store and retrieve a cached matrix inverse makeCacheMatrix <- function(x = matrix()) { - + i <- NULL + set <- function(y) { + x <<- y + i <<- NULL + } + get <- function() x + setinv <- function(inv) i <<- inv + getinv <- function() i + list(set = set, get = get, + setinv = setinv, + getinv = getinv) } -## Write a short comment describing this function +## Returns the inverse of a special matrix +## Uses cached value if available, calculates and caches if not cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + i <- x$getinv() + if(!is.null(i)) { + message("getting cached data") + return(i) + } + data <- x$get() + i <- solve(data, ...) + x$setinv(i) + i }