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/cachematrix.R b/cachematrix.R index a50be65aa44..a53a546b782 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,72 @@ -## Put comments here that give an overall description of what your -## functions do +## Programming assignment 2 +## +## > m <- matrix(rnorm(49),7,7) +## > mc <- makeCacheMatrix(m) +## > cacheSolve(mc) +## [,1] [,2] [,3] [,4] [,5] +## [1,] -0.2335268 0.32422911 0.6239005 0.2368416 -0.36826412 +## [2,] -0.4776660 0.06646721 0.5249364 -1.0634309 0.04139137 +## [3,] 0.1285453 -1.30284238 1.0972079 -2.3344796 0.02208996 +## [4,] -0.2068005 -0.74517115 0.2454044 0.1984123 -0.18916633 +## [5,] -0.1402871 -0.72239385 1.3482179 -1.7596189 -0.49403317 +## [6,] 0.3558382 -0.82380599 0.1844959 -0.4698125 -0.82707022 +## [7,] 0.4052904 -0.83673069 0.8795818 -2.3184046 0.18261628 +## [,6] [,7] +## [1,] -0.18516499 0.9944101 +## [2,] -0.23073671 0.4691068 +## [3,] 0.07649743 0.3722228 +## [4,] -0.18435024 -0.1223557 +## [5,] 0.35501462 0.3422012 +## [6,] 0.24631449 -0.5766368 +## [7,] 0.13758246 -0.0364764 +## > head(cacheSolve(mc),3) +## using cached data +## [,1] [,2] [,3] [,4] [,5] +## [1,] -0.2335268 0.32422911 0.6239005 0.2368416 -0.36826412 +## [2,] -0.4776660 0.06646721 0.5249364 -1.0634309 0.04139137 +## [3,] 0.1285453 -1.30284238 1.0972079 -2.3344796 0.02208996 +## [,6] [,7] +## [1,] -0.18516499 0.9944101 +## [2,] -0.23073671 0.4691068 +## [3,] 0.07649743 0.3722228 -## Write a short comment describing this function +## create a special kind of matrix that will cache the result +## of the solve() function makeCacheMatrix <- function(x = matrix()) { - + # we're going to use that to cache the inverse of the + # matrix provided in parameters + inverse <- NULL + # cache the value of the matrix + set <- function(y) { + x <<- y + # we've just reset the original matrix, so initialize + # the inverse to NULL, so we don't return values from + # previous computations + inverse <<- NULL + } + # return the cached value of the original matrix + get <- function() x + # return the inverse of the cached data + getinverse <- function() { + # check if we have already computed the inverse + if (!is.null(inverse)) { + # YAY ! just return the value we have already computed + message("using cached data") + return(inverse) + } + # else, solve the matrix, store the result and return it + inverse <<- solve(x) + inverse + } + # return a vector containing the different "member" functions + list(set = set, get = get, getinverse = getinverse) } -## Write a short comment describing this function - +## solve a matrix x, using cached data if possible cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + # just call the getinverse() 'member' function, retrieving + # the cached solve(result) if it has already been computed + x$getinverse() }