From de562b06aff4cf1b5e0119ddaaade22d4547cfbb Mon Sep 17 00:00:00 2001 From: Adrian Quek Date: Sun, 27 Sep 2015 15:30:56 +0800 Subject: [PATCH 1/2] Implemented the solution. --- cachematrix.R | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..3a56d8003dc 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -4,6 +4,17 @@ ## Write a short comment describing this function makeCacheMatrix <- function(x = matrix()) { + s <- NULL + set <- function(y) { + x <<- y + s <<- NULL + } + get <- function() x + setinverse <- function(inverse) s <<- inverse + getinverse <- function() s + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } @@ -11,5 +22,14 @@ makeCacheMatrix <- function(x = matrix()) { ## Write a short comment describing this function cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + ## Return a matrix that is the inverse of 'x' + s <- x$getinverse() + if(!is.null(s)){ + message("getting cached inverse") + return(s) + } + data <- x$get() + s <- solve(data, ...) + x$setinverse(s) + s } From c07074336103afee8bf13ca23c5d14726423849d Mon Sep 17 00:00:00 2001 From: Adrian Quek Date: Wed, 30 Sep 2015 22:35:16 +0800 Subject: [PATCH 2/2] Added comments. Didn't think they were necessary, but noticed they were part of the assessment. Oh well. --- cachematrix.R | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/cachematrix.R b/cachematrix.R index 3a56d8003dc..3ff7a3c2e15 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -4,6 +4,11 @@ ## Write a short comment describing this function makeCacheMatrix <- function(x = matrix()) { + # returns a list of functions for: + # - setting the matrix x + # - getting the matrix x + # - setting the inverse of the matrix x (s) + # - getting the inverse of the matrix x s <- NULL set <- function(y) { x <<- y @@ -24,10 +29,12 @@ makeCacheMatrix <- function(x = matrix()) { cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' s <- x$getinverse() + # return cached inverse if it exists if(!is.null(s)){ message("getting cached inverse") return(s) } + # otherwise call solve to get the inverse and set it data <- x$get() s <- solve(data, ...) x$setinverse(s)