Skip to content

Instantly share code, notes, and snippets.

@janzikan
Created May 17, 2017 15:56
Show Gist options
  • Save janzikan/c094b8273986ab21eed154ce61d7e939 to your computer and use it in GitHub Desktop.
Save janzikan/c094b8273986ab21eed154ce61d7e939 to your computer and use it in GitHub Desktop.
R: Generate inverse matrix witch caching
# Provide getter and setter methods for the given matrix and its
# inverse that is cached in a variable.
makeCacheMatrix <- function(x = matrix()) {
# Variable used for caching
inverse <- NULL
# Set
set <- function(y) {
x <<- y
# Clean the cache
inverse <<- NULL
}
# Get the original (not inverted) matrix
get <- function() {
x
}
# Store matrix to the cache
setInverse <- function(inv) {
inverse <<- inv
}
# Get inverse matrix from cache
getInverse <- function() {
inverse
}
# Return all defined functions in a list
list(set = set, get = get, setinverse = setInverse, getinverse = getInverse)
}
# Get matrix that is inverse of 'x'
# Function is using functions provided by makeCacheMatrix function to
# retrieve inverted matrix from cache if it present there.
# Example:
# mx <- matrix(1:4, nrow = 2, ncol = 2)
# cached_mx <- makeCacheMatrix(mx)
# cacheSolve(cached_mx)
cacheSolve <- function(x) {
## Return a matrix that is the inverse of 'x'
inverse <- x$getinverse()
# Get cached inverse matrix
if(!is.null(inverse)) {
return(inverse)
}
data <- x$get()
inverse <- solve(data)
# Cache the result
x$setinverse(inverse)
inverse
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment