diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..50c9a1005e4 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,41 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## makeCacheMatrix creates a special matrix that can keep the +## original matrix and inverse of the matrix (if set) +## cacheSolve receives an instance of makeCacheMatrix and +## checks if inverse is available in cache. If not, computes the inverse, +## saves to the cache, and return the result +## This function wraps a matrix and returns a list of +## operation to set and get the matrix and it's inverse matrix makeCacheMatrix <- function(x = matrix()) { - + inverseMatrix <- NULL + set <- function(inputMatrix) { + x <<- inputMatrix + inverseMatrix <<- NULL + } + get <- function() x + setInverse <- function(inverseM) inverseMatrix <<- inverseM + getInverse <- function() { + inverseMatrix + } + list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } -## Write a short comment describing this function + +## This function returns the inverse of matrix stored in parameter +## It first checks for cache, if not availalbe, computes the cache. +## Otherwise just returns from the cache. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + + inverseMatrix <- x$getInverse() + + if(!is.null(inverseMatrix)) { ## Found in cache + return(inverseMatrix) + } + + m <- x$get() + inverseMatrix <- solve(m) + x$setInverse(inverseMatrix) + inverseMatrix }