diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..a29fbfc0059 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,37 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## This is a couple of functions which is used to cache +## inverse of a matrix +## Creates a special object to store inverse of a matrix makeCacheMatrix <- function(x = matrix()) { - + inv <- NULL + + ## get & set original matrix + set <- function(m) { + x <<- m + inv <<- NULL + } + get <- function() x + + ## get & set the inverse of a matrix + setinv <- function(inverse) inv <<- inverse + getinv <- function() inv + + list(set = set, get = get, setinv = setinv, getinv = getinv) } -## Write a short comment describing this function - +## Returns the inverse of matrix 'x'. +## If the inverse is not present in cache, will calculate it and store to cache. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + inv <- x$getinv() + + if(!is.null(inv)) { + message("getting cached data") + return (inv) + } + data <- x$get() + inv = solve(data, ...) + x$setinv(inv) + + inv }