From 432f25aa8758ad7dc18b584fd0aa51173a1d29c2 Mon Sep 17 00:00:00 2001 From: maxeywen Date: Mon, 28 Apr 2014 10:21:25 +0800 Subject: [PATCH] Update cachematrix.R completed functions makeCacheMatrix() cacheSolve() added comments --- cachematrix.R | 43 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..349a39b8c98 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,44 @@ -## Put comments here that give an overall description of what your -## functions do +## 2 functions that will accept a matrix, calculate its inverse, cache the result, +## and return the cached inverse unless the original matrix is changed -## Write a short comment describing this function +## makeCacheMatrix() +## exposes 4 methods in a list +## set, get, setInverse, getInverse makeCacheMatrix <- function(x = matrix()) { - + i <- NULL + + set <- function(y) { + x <<- y + i <<- NULL + } + + get <- function() x + + setInverse <- function(inv) i <<- inv + + getInverse <- function() i + + list(set = set, get = get, + setInverse = setInverse, + getInverse = getInverse) } -## Write a short comment describing this function +## checks cache first for inverse. if cache is NULL, +## solves the matrix and stores in cache -cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' +cacheSolve <- function(x) { + ## Return a matrix that is the inverse of 'x' + + i <- x$getInverse() + if(!is.null(i)) { + message("getting cached data") + return(i) + } + + data <- x$get() + i <- solve(data) + x$setInverse(i) + i }