From 19f55639a38d2d88b55096a5596ea51fa9b9dcc9 Mon Sep 17 00:00:00 2001 From: Sheroy Marker Date: Sat, 21 Jun 2014 15:14:43 -0700 Subject: [PATCH] Functions to add the ability to cache the inverse of a Matrix --- cachematrix.R | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..bd0050c3980 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,30 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## Set of functions to add the ability to cache the inverse of the Matrix and to +## use the cached value while getting the inverse of a Matrix +## Adds the ability to cache the inverse of the matrix passed in as a paramter to this## function makeCacheMatrix <- function(x = matrix()) { - + inverse <- NULL + set <- function(y) { + x <<- y + inverse <<- NULL + } + get <- function() x + setinverse <- function(i) inverse <<- i + getinverse <- function() inverse + list(get = get, set = set, getinverse = getinverse, setinverse = setinverse) } -## Write a short comment describing this function - +## Gets the inverse of the Matrix and caches the result if required. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + i <- x$getinverse() + if (! is.null(i)) { + message("Getting cached inverse") + return(i) + } + m <- x$get() + i <- solve(m, ...) + x$setinverse(i) + i }