Mic*_*ick 4 closures caching r
我正在关注Coursera上的数据科学课程,我有一个关于其中一个分配的问题,我必须反转矩阵,然后缓存该结果.
基本上我一直在谷歌搜索,我找到了答案,但有部分答案,我还不明白.出于这个原因,我不想提交我的作业,因为我不想提交任何我不完全理解的内容.
我从下面的代码中无法理解的部分是定义setInverse的部分.'function(inverse)inv'来自哪里?特别是'逆'从未被定义过?
在此之后返回一个对我来说没有多大意义的列表?
如果有人可以花时间向我解释这个功能,我将非常感激!
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
}
Run Code Online (Sandbox Code Playgroud)
我不知道你的具体任务,但我会略微改变你的功能:
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)
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
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
Run Code Online (Sandbox Code Playgroud)
练习可能是为了教你封闭.的一点是,x与inv存储在的封闭环境set,get,setInverse,getInverse的功能.这意味着定义它们的环境,即makeCacheMatrix()呼叫创建的环境.看到这个:
ls(environment(funs$set))
#[1] "get" "getInverse" "inv" "set" "setInverse" "x"
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,不仅是这个环境中的四个函数,还有对象x和inv对象(使用的结果<<-).而get和getInverse功能只能从他们的封闭环境中获取这些.