Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 34 additions & 10 deletions cachematrix.R
Original file line number Diff line number Diff line change
@@ -1,15 +1,39 @@
## Put comments here that give an overall description of what your
## functions do

## Write a short comment describing this function

makeCacheMatrix <- function(x = matrix()) {

inv <- NULL # this will store the inverse later

# 1. set() - set a new matrix and reset cached inverse
set <- function(y) {
x <<- y
inv <<- NULL
}

# 2. get() - get the current matrix
get <- function() x

# 3. setinverse() - store (cache) the inverse
setinverse <- function(inverse) inv <<- inverse

# 4. getinverse() - get the cached inverse
getinverse <- function() inv

# return a list of all 4 functions
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'
inv <- x$getinverse() # check if inverse already cached

if (!is.null(inv)) { # if yes, just return it
message("getting cached data")
return(inv)
}

# if not cached, calculate it
data <- x$get()
inv <- solve(data, ...) # compute inverse
x$setinverse(inv) # store inverse in cache

inv # return the result
}