diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..e0c02eb3662 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,34 @@ -## Put comments here that give an overall description of what your -## functions do -## Write a short comment describing this function -makeCacheMatrix <- function(x = matrix()) { +## This function creates a matrix object that can cache its inverse +makeCacheMatrix <- function(x = matrix()) { + m <- NULL + set <- function(y) { # sets the variables x and y + x <<- y + m <<- NULL + } + get <- function() x #gets x + setInverse <- function(inverse) m <<- inverse #sets the inverse to m + getInverse <- function() m #gets m + list(set = set, get = get, + setInverse = setInverse, + getInverse = getInverse) } - - -## Write a short comment describing this function - +#This function computes the inverse of the matrix, +#if it has not been computed before or +#retrieves the answer that has been already calculated cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + m <- x$getInverse()#get inverse or NULL if it has not been computed before + + if(!is.null(m)) {# if the inverse has been computed before, return that inverse + message("getting cached inverse") + return(m) + } + data <- x$get() + m <- solve(data, ...)#compute inverse if it has not been computed before + x$setInverse(m) + m } + +