diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..1174ca5054b 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,40 @@ ## Put comments here that give an overall description of what your ## functions do -## Write a short comment describing this function - +## returns a list of functions to get/set an 'internal' matrix and get/set its inverse. +## (get, set, getinv, setinv). +## If the matrix is 'set' via this list's set function, the inverse matrix will be cleared. makeCacheMatrix <- function(x = matrix()) { + m <- NULL + set <- function(y) { + x <<- y + m <<- NULL + } + get <- function() x + setinv <- function(matinv) m <<- matinv + getinv <- function() m + list(set = set, get = get, + setinv = setinv, + getinv = getinv) } -## Write a short comment describing this function - +## Returns inverse of x, storing the computation of the inverse +## x is not actually a matrix, but rather a list generated by makeCacheMatrix +## This will set the 'internal' inverse matrix for mackCacheMatrix context if +## it doesn't already exist, and will simply return that matrix if it exists w/o +## recomputing. cacheSolve <- function(x, ...) { + + m <- x$getinv() + if(!is.null(m)) { + message("getting cached data") + return(m) + } + data <- x$get() + m <- solve(data) + x$setinv(m) + m ## Return a matrix that is the inverse of 'x' } diff --git a/test.R b/test.R new file mode 100644 index 00000000000..8c1d7442748 --- /dev/null +++ b/test.R @@ -0,0 +1,11 @@ +source('./cachematrix.R') +x <- matrix(c(2,2,3,2), nrow=2, ncol=2) +y <- matrix(c(1, -1, 1, 2), nrow=2, ncol=2) +cmx <- makeCacheMatrix(x) +cmy <- makeCacheMatrix(y) +invx <- cacheSolve(cmx) +invy <- cacheSolve(cmy) +solve(cacheSolve(cmy)) +solve(cacheSolve(cmx)) +solve(cacheSolve(cmy)) +solve(cacheSolve(cmx))