diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..9843be17d37 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,35 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## Computes and caches the inverse of a square matrix. +## +## Two methods are exposed: +## makeCacheMatrix creates or wraps a matrix to cache its inverse +## cacheSolve returns the cached inverse if available, or computes and caches it otherwise. +## Creates or wraps a matrix to cache its inverse makeCacheMatrix <- function(x = matrix()) { - + i <- NULL + set <- function(y) { + x <<- y + i <<- NULL + } + get <- function() x + setinverse <- function(inverse) i <<- inverse + getinverse <- function() i + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } -## Write a short comment describing this function - +## Returns the cached inverse if available, or computes and caches it otherwise. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' -} + inverse <- x$getinverse() + if(!is.null(inverse)) { + message("getting cached data") + return(inverse) + } + data <- x$get() + inverse <- solve(data, ...) + x$setinverse(inverse) + inverse +} \ No newline at end of file