diff --git a/.Rhistory b/.Rhistory new file mode 100644 index 00000000000..054ee17affe --- /dev/null +++ b/.Rhistory @@ -0,0 +1,26 @@ +## This function creates a special "matrix" object that can cache its inverse. +makeCacheMatrix <- function(x = matrix()) { +inv <- NULL # initialize inverse as NULL +set <- function(y) { +x <<- y # assign new matrix value +inv <<- NULL # reset inverse cache +} +get <- function() x +setinverse <- function(inverse) inv <<- inverse +getinverse <- function() inv +list(set = set, get = get, +setinverse = setinverse, +getinverse = getinverse) +} +## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. +cacheSolve <- function(x, ...) { +inv <- x$getinverse() +if(!is.null(inv)) { +message("getting cached data") +return(inv) # return cached inverse +} +data <- x$get() +inv <- solve(data, ...) # compute inverse +x$setinverse(inv) # cache the inverse +inv +} diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..5b43f08d60b 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,27 @@ -## Put comments here that give an overall description of what your -## functions do - -## Write a short comment describing this function - +## This function creates a special "matrix" object that can cache its inverse. makeCacheMatrix <- function(x = matrix()) { - + inv <- NULL # initialize inverse as NULL + set <- function(y) { + x <<- y # assign new matrix value + inv <<- NULL # reset inverse cache + } + get <- function() x + setinverse <- function(inverse) inv <<- inverse + getinverse <- function() inv + list(set = set, get = get, + setinverse = setinverse, + getinverse = getinverse) } - -## Write a short comment describing this function - +## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' + inv <- x$getinverse() + if(!is.null(inv)) { + message("getting cached data") + return(inv) # return cached inverse + } + data <- x$get() + inv <- solve(data, ...) # compute inverse + x$setinverse(inv) # cache the inverse + inv }