diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..b4d592d70f1 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,49 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## makeCacheMatrix creates a special "vector", +# which is really a list containing a function to +# a) set the value of the matrix +# b) get the value of the matrix +# c) set the value of the inverse of the matrix +# d) get the value of the inverse of the matrix makeCacheMatrix <- function(x = matrix()) { - + inv <- NULL + ## Update existing matrix + set <- function(y){ + x <<- y + inv <<- NULL + } + ## Return original matrix + get <- function() x + ### Set the inverse of the matrix + setinverse <- function(inverse) inv <<- inverse + ### Return the inverse of the matrix + getinverse <- function() inv + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } - -## Write a short comment describing this function +## cacheSolve performs following tasks: +# 1) check if inverse of the matrix is already created or not +# 2) return the inverse of the matrix if cached inverse found +# 3) compute inverse of the matrix if no cache found +# 4) cache the inverse of the matrix +# 5) return the inverse of the matrix cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + inv <- x$getinverse() + ## check if inverse of the matrix is cached + if(!is.null(inv)) { + ## return cache if cache is found + message("getting cached data") + return(inv) + } + ## if cache is not found, then get the inverse of the matrix. + ## first, get the original matrix + data <- x$get() + ## then get a inverse + inv <- solve(data, ...) + ### cache retrieved value + x$setinverse(inv) + inv }