diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..8d4a5c643a6 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,41 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function +## function makeCacheMatrix() creates a special "matrix" object that can cache its inverse. +## There are several functions: +## 1. set the value of the matrix +## 2. get the value of the matrix +## 3. set the inverse of the matrix +## 4. get the inverse of the matrix 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) } +## cacheSolve() computes the inverse of the special "matrix" returned by makeCacheMatrix above. +## If the inverse has already been calculated (and the matrix has not changed), then the cachesolve +## should retrieve the inverse from the cache. +cacheSolve <- function(x, ...) { + m <- x$getInverse() -## Write a short comment describing this function + ## Return a matrix that is the inverse of 'x' if the inverse has already been calculated and cached. + if(!is.null(m)) { + message("getting cached data") + return(m) + } -cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Calculate the inverse of 'x' if the cached data doesn't exist. + data <- x$get() + m <- solve(data, ...) + x$setInverse(m) + + ## Return a matrix that is the inverse of 'x' + m }