From 0c2789b1befaf8b3d46110da9b454a7cebc1a0ba Mon Sep 17 00:00:00 2001 From: Jack Bates Date: Sun, 16 Apr 2017 10:59:34 -0700 Subject: [PATCH] My solution! --- cachematrix.R | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..eacf04104f0 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,25 @@ -## Put comments here that give an overall description of what your -## functions do +## Invert a matrix and cache the result, to demonstrate the power of +## environments in R! -## Write a short comment describing this function - -makeCacheMatrix <- function(x = matrix()) { +## Construct a special "matrix" object that can cache its own inverse. +makeCacheMatrix <- function (x = matrix()) { + inverse <- NULL + list(get = function () x, + getinverse = function () inverse, + setinverse = function (inverse) inverse <<- inverse) } -## Write a short comment describing this function +## Compute the inverse of a special "matrix" returned by +## makeCacheMatrix(), above. Only calculate the result once -- stow the +## result for next time and just return the cached value, if available. -cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' +cacheSolve <- function (x) { + inverse <- x$getinverse() + if (is.null(inverse)) { + x$setinverse(solve(x$get())) + } else { + inverse + } }