diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..6b6ed6fe22c 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,41 @@ -## Put comments here that give an overall description of what your -## functions do +## This function creates a list comprising of 4 functions: -## Write a short comment describing this function +## set <- sets matrix x in the makeCacheMatrix context +## and clears the previous cached inverse (m) -makeCacheMatrix <- function(x = matrix()) { +## get <- gets matrix x in the makeCacheMatrix context -} +## setinverse <- sets cached inverse m in the makeCacheMatrix context + +## getinverse <- cached inverse m in the makeCacheMatrix context +makeCacheMatrix <- function(x = matrix()) { + m <- NULL + set <- function(y) { + x <<- y + m <<- NULL + } + get <- function() x + setinverse <- function(solve) m <<- solve + getinverse <- function() m + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) +} -## Write a short comment describing this function +## This function checks whether the inverse was already calculated and cached +## If that's the case, just returns the cached value +## Otherwise, calculates the inverse via solve function, caches and returns it cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' + m <- x$getinverse() + if (!is.null(m)) { + message("getting cached data") + return(m) + } + data <- x$get() + m <- solve(data, ...) + x$setinverse(m) + m }