From 455be9eab47fbcbb74d687d6c177c042a37f7c97 Mon Sep 17 00:00:00 2001 From: Nicolas Zabel Date: Fri, 18 Apr 2014 15:41:14 +0200 Subject: [PATCH 1/2] completed assignment --- cachematrix.R | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..b2a186c2154 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,34 @@ -## Put comments here that give an overall description of what your -## functions do +## Cache the result of solve in an internal structure along with the matrix -## Write a short comment describing this function -makeCacheMatrix <- function(x = matrix()) { +## makeCacheMatrix is a closure that defines the accessors +## and the mutators of a matrix (x) and its inverse (i) +makeCacheMatrix <- function(x = matrix()) { + i <- NULL # inverse of the matrix (cache) + set <- function(y) { + x <<- y # assign the new matrix y to x, the internal store of the matrix + i <<- NULL # invalidate the cached inverse of the matrix x + } + get <- function() x # return the value of the matrix x + setSolved <- function(j) i <<- j # cache the inverse of the matrix x + getSolved <- function() i # return the value of the inverse + list(get = get, set = set, getSolved = getSolved, setSolved = setSolved) } -## Write a short comment describing this function +## Cache the result of solve (ie the inverse of x) into its internal variable i cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' -} + ## Return a matrix that is the inverse of 'x' + i <- x$getSolved() # retrieve the cached inverse + if (!is.null(i)) { + # the cached inverse has not been invalidated by an update (x$set) of the matrix + message("getting cached data") + return (i) + } + m <- x$get() # retrieve the data of the matrix + i <- solve(m,...) + x$setSolved(i) + i +} \ No newline at end of file From 2a0cae93379b4d27ab2a196980877b92a3713141 Mon Sep 17 00:00:00 2001 From: Nicolas Zabel Date: Fri, 18 Apr 2014 15:48:29 +0200 Subject: [PATCH 2/2] more comments --- cachematrix.R | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index b2a186c2154..5380dacfabe 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -28,7 +28,7 @@ cacheSolve <- function(x, ...) { return (i) } m <- x$get() # retrieve the data of the matrix - i <- solve(m,...) - x$setSolved(i) - i -} \ No newline at end of file + i <- solve(m,...) # compute the inverse + x$setSolved(i) # cache the inverse + i # return the inverse +}