From 63d6df1fc7881a54f1ad1383c50b112ce92f1b78 Mon Sep 17 00:00:00 2001 From: Adam Benzan Date: Mon, 17 Nov 2014 16:40:01 -0500 Subject: [PATCH 1/2] seems to work --- cachematrix.R | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..3140cf0cc74 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,30 @@ -## Put comments here that give an overall description of what your + ## Put comments here that give an overall description of what your ## functions do ## Write a short comment describing this function makeCacheMatrix <- function(x = matrix()) { - + m <- NULL + set <- function(y) { + x <<- y + m <<- NULL + } + get <- function() x + setinverse <- function(inverse) m <<- inverse + getinverse <- function() m + list(set = set, get = get, setinverse=setinverse, getinverse=getinverse) } ## Write a short comment describing this function cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + m <- x$getinverse() + if (!is.null(m)) { + message('cached inverse') + return(m) + } + m <- solve(x$get()) + x$setinverse(m) + m } From 6b29f729a86ebcadd8a6bafff2aedda8f60545c1 Mon Sep 17 00:00:00 2001 From: Adam Benzan Date: Mon, 17 Nov 2014 16:49:44 -0500 Subject: [PATCH 2/2] add comments --- cachematrix.R | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index 3140cf0cc74..6f958c6d465 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,30 +1,29 @@ - ## Put comments here that give an overall description of what your -## functions do +## cachematrix: Functions to cache matrix inversion -## Write a short comment describing this function +## makeCacheMatrix sets up the scope for storing cache makeCacheMatrix <- function(x = matrix()) { - m <- NULL - set <- function(y) { + m <- NULL # initialize cache to NULL + set <- function(y) { # changing value invalidates cache x <<- y m <<- NULL } - get <- function() x - setinverse <- function(inverse) m <<- inverse - getinverse <- function() m + get <- function() x # return original matrix + setinverse <- function(inverse) m <<- inverse # set cache value to supplied value + getinverse <- function() m list(set = set, get = get, setinverse=setinverse, getinverse=getinverse) } - -## Write a short comment describing this function +## cacheSolve takes the list generated by makeCacheMatrix and either populates its cache +## or returns the cached value cacheSolve <- function(x, ...) { - m <- x$getinverse() + m <- x$getinverse() # returns NULL if not yet cached if (!is.null(m)) { - message('cached inverse') + message('cached inverse') # report that returned value is from cache return(m) } - m <- solve(x$get()) + m <- solve(x$get()) # uses solve to get inverse of x x$setinverse(m) m }