diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000000..807ea251739 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.Rproj.user +.Rhistory +.RData diff --git a/ProgrammingAssignment2.Rproj b/ProgrammingAssignment2.Rproj new file mode 100644 index 00000000000..8e3c2ebc99e --- /dev/null +++ b/ProgrammingAssignment2.Rproj @@ -0,0 +1,13 @@ +Version: 1.0 + +RestoreWorkspace: Default +SaveWorkspace: Default +AlwaysSaveHistory: Default + +EnableCodeIndexing: Yes +UseSpacesForTab: Yes +NumSpacesForTab: 2 +Encoding: UTF-8 + +RnwWeave: Sweave +LaTeX: pdfLaTeX diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..c4cf826b08a 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,40 @@ -## Put comments here that give an overall description of what your -## functions do +## The makeCacheMatrix and cacheSolve functions work together to create a +## special matrix wrapper object that can cache its own inverse value. -## Write a short comment describing this function +## The makeCacheMatrix function creates a special object that wraps a matrix +## object and provides accessor functions to the matrix object and the cached +## inverse of the matrix. makeCacheMatrix <- function(x = matrix()) { - + i <- NULL + + set <- function(y) { + # Clear the cached inverse whenever we update the matrix object to make + # sure we don't return an incorrect inverse. + message("clearing the cached inverse") + i <<- NULL + x <<- y + } + get <- function() x + setinverse <- function(inverse) i <<- inverse + getinverse <- function() i + list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } -## Write a short comment describing this function +## The cacheSolve function calculates the inverse of the given matrix and +## caches it on that object. If the inverse of the give matrix is already +## cached it returns instead of calculating it anew. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + i <- x$getinverse() + if (!is.null(i)) { + message("getting cached data") + return(i) + } + data <- x$get() + i <- solve(data, ...) + x$setinverse(i) + i }