JHU Coursera Rprogramming Assignment 2

Programming Assignment 2 函数与缓存作业

JHU DataScience Specialization/Cousers R Programming/Week2/Programming Assignment 2

This two functions below are used to create a special object that stores a numeric matrix and cache’s its inverse

第一步编写一个函数存储四个函数

makeCacheMatrix creates a list containing a function to 1. set the value of the matrix 2. get the value of the matrix 3. set the value of inverse of the matrix 4. get the value of inverse of the matrix

1
2
3
4
5
6
7
8
9
10
11
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)
}

第二步其实就是编写读取函数,包括读取缓存功能

The following function return a inverse of special “matirx” created with the above function.However, it first checks to see if the inverse has already been calculated.If so, it gets the inverse from the cache and skips the computation.Otherwise, it calculates the inverse of the matrix and sets the value of the inverse in the cache via the set_inverse function.

1
2
3
4
5
6
7
8
9
10
11
12
# 输出矩阵的逆,执行第二次已经有缓存数据
cacheSolve <- function(x, ...) {
inv <- x$getinverse()
if(!is.null(inv)) {
message("getting cached data.")
return(inv)
}
data <- x$get()
inv <- solve(data)
x$setinverse(inv)
inv
}

验证示例

1
2
#测试输入一个矩阵
(A = matrix(rnorm(9),3,3))
1
2
3
4
##            [,1]      [,2]       [,3]
## [1,] -0.4844660 1.853864 -1.2807958
## [2,] 1.8515872 -1.095139 0.5000131
## [3,] -0.5018424 -2.402839 -0.6736777
1
(B = makeCacheMatrix(A))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
## $set
## function (y)
## {
## x <<- y
## inv <<- NULL
## }
## <environment: 0x000000002fbd8068>
##
## $get
## function ()
## x
## <environment: 0x000000002fbd8068>
##
## $setinverse
## function (inverse)
## inv <<- inverse
## <environment: 0x000000002fbd8068>
##
## $getinverse
## function ()
## inv
## <environment: 0x000000002fbd8068>
1
B$get() #和上面的A是一样
1
2
3
4
##            [,1]      [,2]       [,3]
## [1,] -0.4844660 1.853864 -1.2807958
## [2,] 1.8515872 -1.095139 0.5000131
## [3,] -0.5018424 -2.402839 -0.6736777
1
cacheSolve(B)#第一次
1
2
3
4
##            [,1]       [,2]        [,3]
## [1,] 0.2652819 0.5918507 -0.06507397
## [2,] 0.1363119 -0.0432807 -0.29127964
## [3,] -0.6838065 -0.2865157 -0.39699271
1
cacheSolve(B)#第二次
1
## getting cached data.
1
2
3
4
##            [,1]       [,2]        [,3]
## [1,] 0.2652819 0.5918507 -0.06507397
## [2,] 0.1363119 -0.0432807 -0.29127964
## [3,] -0.6838065 -0.2865157 -0.39699271
THE END