From 309e3fab61447dfb7fa07789409ee3551dea9354 Mon Sep 17 00:00:00 2001 From: Rob Baker Date: Wed, 1 Jun 2016 00:18:19 -0400 Subject: [PATCH] homework --- cachematrix.R | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..759e6af7493 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -4,12 +4,42 @@ ## Write a short comment describing this function makeCacheMatrix <- function(x = matrix()) { + inv <- NULL + set <- function(y){ + x <<- y + inv <<- NULL + } + + get <- function() x + setinv <- function(solve) inv <<- solve + getinv <- function() inv + list(set = set, get = get, setinv = setinv, getinv = getinv) } -## Write a short comment describing this function +# This function delivers the inverted matrix from makeCacheMatrix, +# first looking for a cached version and if not there +# computing and returning the inversion. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + # Return an inverted matrix of the passed matrix. + inv <- x$getinv() + + # Look for a cached version + if(!is.null(inv)) { + message("Aw yiss, a cached version.") + return(inv) + } + + # Otherwise invert the matrix. + data <- x$get() + inv <- solve(data, ...) + x$setinv(inv) + inv } + +# Test it out +test <- makeCacheMatrix() +test$set(matrix(c(1:4),2,2)) +cacheSolve(test)