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
34 changes: 30 additions & 4 deletions cachematrix.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,40 @@
## functions do

## Write a short comment describing this function

# makeCacheMatrix: create a matrix that can store itself and a cached copy of its inverse once its computed
makeCacheMatrix <- function(x = matrix()) {

inv <- NULL # cache for inverse

set <- function(y) { # replace matrix and reset cache
x <<- y
inv <<- NULL
}

get <- function() x # return current matrix

setinverse <- function(inverse) # store computed inverse
inv <<- inverse

getinverse <- function() inv # return cached inverse (or NULL)

list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}


## Write a short comment describing this function

## Write a short comment describing this function
# cacheSolve: returns the cached inverse or computes & caches it
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getinverse() # try cache first
if (!is.null(inv)) {
message("getting the cached inverse")
return(inv)
}
mat <- x$get() # fetch matrix
inv <- solve(mat, ...) # compute inverse (assumes invertible)
x$setinverse(inv) # cache result
inv # return inverse
}