I am following a Data Science course on Coursera and I have a question regarding one of the assignments where I have to inverse a Matrix and then cache that result.
Basically I have been googling away and I found the answer but there are parts of the answer that I do not yet understand. For this reason I don't want to submit my assignment yet since I don't want to submit anything that I do not fully understand.
The part that I do not understand from the code below is the part where setInverse is defined. where does the 'function(inverse) inv' come from? especially the 'inverse' was never defined?
After this a list is returned which does not make much sense to me as well?
If someone could take the time to explain this function to me I would be very grateful!
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
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
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)
}
mat <- x$get()
inv <- solve(mat, ...)
x$setInverse(inv)
inv
}
I don't know your exact assignment, but I would change your function slightly:
You can then use it like this:
The exercise is probably intended to teach you closures. The point is that
x
andinv
are stored in the enclosing environment of theset
,get
,setInverse
,getInverse
functions. That means the environment within which they were defined, i.e., the environment created by themakeCacheMatrix()
call. See this:As you see not only are the four functions in this environment, but also the
x
andinv
objects (a consequence of using<<-
). And theget
andgetInverse
functions only fetch these from their enclosing environment.