diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..a8e0dd5d5b0 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,50 @@ -## Put comments here that give an overall description of what your -## functions do +## Cache matrix inversion -## Write a short comment describing this function +## Create a matrix object to cache it's inverse +## Example of usage cacheSolve(makeCacheMatrix(matrix(c(1, 3, 2, 4), 2,2))) makeCacheMatrix <- function(x = matrix()) { - + + m <- NULL + + set <- function (y) { + x <<- y + m <<- NULL + } + + get <- function () { + x + } + + setInverse <- function (inverseMatrix) { + + if (hasArg(inverseMatrix)) + # Set inversed matrix + m <<- inverseMatrix + else + # Invert current matrix + m <<- solve(x) + } + + getInverse <- function () { + m + } + + list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } -## Write a short comment describing this function +## Returns a matrix inverted from x +## x should come from makeCacheMatrix cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + + m <- x$getInverse() + + if (is.null(m)) { + m <- solve(x$get()) + x$setInverse(m) + } + + m }