diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..d7402eb1f87 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,35 @@ -## Put comments here that give an overall description of what your -## functions do +## These two functions create a matrix and then the inverse of the matrix. +## The inverse is cached and if the same matrix is inverted it will read +## the cached version. ## Write a short comment describing this function - + # This function supplies setter and getter methods for the + # original matrix and the inverse makeCacheMatrix <- function(x = matrix()) { - + matrix <- NULL + setMatrix <- function(y) { + x <<- y + matrix <<- NULL + } + getMatrix <- function() x + setMatrixInverse <- function(cacheMatrix) matrix <<- cacheMatrix + getMatrixInverse <- function() matrix + list(setMatrix = setMatrix, getMatrix = getMatrix, + setMatrixInverse = setMatrixInverse, getMatrixInverse = getMatrixInverse) } - ## Write a short comment describing this function - + # This function checks to see if there is already a matrix stored + # in the variable matrix then returns the cached version if it exists + # or creates one if it does not. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + matrix <- x$getMatrixInverse() + if(!is.null(matrix)) { + message("getting cached data") + return(matrix) + } + data <- x$getMatrix() + cacheMatrix <- solve(data, ...) + x$setMatrixInverse(cacheMatrix) + cacheMatrix } diff --git a/makeVector.R b/makeVector.R new file mode 100644 index 00000000000..66ad7d247e6 --- /dev/null +++ b/makeVector.R @@ -0,0 +1,23 @@ +makeVector <- function(x = numeric()) { + m <- NULL + set <- function(y) { + x <<- y + m <<- NULL + } + get <- function() x + setmean <- function(mean) m <<- mean + getmean <- function() m + list(set = set, get = get, setmean = setmean, getmean = getmean) +} + +cachemean <- function(x, ...) { + m <- x$getmean() + if(!is.null(m)) { + message("getting cached data") + return(m) + } + data <- x$get() + m <- mean(data, ...) + x$setmean(m) + m +} \ No newline at end of file