R programming: cache the inverse of a matrix

2019-01-12 04:33发布

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
}

1条回答
做自己的国王
2楼-- · 2019-01-12 05:03

I don't know your exact assignment, but I would change your function slightly:

makeCacheMatrix <- function(x = matrix()) {
  inv <- NULL
  set <- function(y) {
    x <<- y
    inv <<- NULL
  }
  get <- function() x
  setInverse <- function() inv <<- solve(x) #calculate the inverse
  getInverse <- function() inv
  list(set = set,
       get = get,
       setInverse = setInverse,
       getInverse = getInverse)
}

You can then use it like this:

funs <- makeCacheMatrix()
funs$set(matrix(1:4, 2))
funs$get()
#     [,1] [,2]
#[1,]    1    3
#[2,]    2    4
funs$setInverse()
funs$getInverse()
#     [,1] [,2]
#[1,]   -2  1.5
#[2,]    1 -0.5

The exercise is probably intended to teach you closures. The point is that x and inv are stored in the enclosing environment of the set, get, setInverse, getInverse functions. That means the environment within which they were defined, i.e., the environment created by the makeCacheMatrix() call. See this:

ls(environment(funs$set))
#[1] "get"        "getInverse" "inv"        "set"        "setInverse" "x"

As you see not only are the four functions in this environment, but also the x and inv objects (a consequence of using <<-). And the get and getInverse functions only fetch these from their enclosing environment.

查看更多
登录 后发表回答