diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..219aa992cf9 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,33 @@ -## Put comments here that give an overall description of what your -## functions do +## makeCacheMatrix is a function that creats a special matrix, which contains functions such as getMatrix, +## setMatrix, setInverse, and getInverse. With those functions you can get or set the matrix and get or set +## the inverse of the matrix, respectively. -## Write a short comment describing this function makeCacheMatrix <- function(x = matrix()) { - + inverse <- NULL + setMatrix <- function(y,...){ + x <<- matrix(y,...) + inverse <<- NULL + } + getMatrix <- function() x + setInverse <- function(MatrixInverse) inverse <<- MatrixInverse + getInverse <- function() inverse + list(setMatrix = setMatrix, getMatrix = getMatrix, + setInverse = setInverse, getInverse = getInverse) } -## Write a short comment describing this function +## Function'cacheSolve' either obtains the invers of a previous special matrix, if it is already calculated +## and cached in special matrix, or the function calculates the inverse in situ and stores in special matrix. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + inverse <- x$getInverse() + if(!is.null(inverse)) { + message("getting cached inverse") + return(inverse) + } + data <- x$getMatrix() + inverse <- solve(data, ...) + x$setInverse(inverse) + inverse }