From 3c55327a6026ee8ff85490f96c5aea05b6d8c12e Mon Sep 17 00:00:00 2001 From: Daniel Cheah Date: Mon, 15 Sep 2014 14:38:40 -0700 Subject: [PATCH] Finished solution for the cache matrix problem. --- cachematrix.R | 42 +++++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..bffd08b1a36 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,31 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function - -makeCacheMatrix <- function(x = matrix()) { - +## Creates a matrix object that enables caching +## of inverse matrix. +makeCacheMatrix <- function(mat = matrix()) { + inverse <- NULL + set <- function(x) { + mat <<- x + inverse <<- NULL + } + get <- function() mat + setinverse <- function(x) inverse <<- x + getinverse <- function() inverse + 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' -} +## Solves for inverse matrix and caches it +cacheSolve <- function(mat, ...) { + ## Checks if the inverse matrix has been calculated + inverse <- mat$getinverse() + if(!is.null(inverse)) { + message("getting cached data") + return(inverse) + } + ## Inverse has not been calculated. + ## Solve and then cache result. + data <- mat$get() + inverse <- solve(data, ...) + mat$setinverse(inverse) + inverse +} \ No newline at end of file