1
- # #Second GIT Project
2
- # # Put comments here that give an overall description of what your
3
- # # functions do
4
-
5
- # # Write a short comment describing this function
6
-
7
1
makeCacheMatrix <- function (x = matrix ()) {
8
-
2
+ # # @x: a square invertible matrix
3
+ # # return: a list containing functions to
4
+ # # 1. set the matrix
5
+ # # 2. get the matrix
6
+ # # 3. set the inverse
7
+ # # 4. get the inverse
8
+ # # this list is used as the input to cacheSolve()
9
+
10
+ inv = NULL
11
+ set = function (y ) {
12
+ # use `<<-` to assign a value to an object in an environment
13
+ # different from the current environment.
14
+ x <<- y
15
+ inv <<- NULL
16
+ }
17
+ get = function () x
18
+ setinv = function (inverse ) inv <<- inverse
19
+ getinv = function () inv
20
+ list (set = set , get = get , setinv = setinv , getinv = getinv )
9
21
}
10
22
23
+ cacheSolve <- function (x , ... ) {
24
+ # # @x: output of makeCacheMatrix()
25
+ # # return: inverse of the original matrix input to makeCacheMatrix()
26
+
27
+ inv = x $ getinv()
28
+
29
+ # if the inverse has already been calculated
30
+ if (! is.null(inv )){
31
+ # get it from the cache and skips the computation.
32
+ message(" getting cached data" )
33
+ return (inv )
34
+ }
35
+
36
+ # otherwise, calculates the inverse
37
+ mat.data = x $ get()
38
+ inv = solve(mat.data , ... )
39
+
40
+ # sets the value of the inverse in the cache via the setinv function.
41
+ x $ setinv(inv )
42
+
43
+ return (inv )
44
+ }
11
45
12
- # # Write a short comment describing this function
46
+ # #Test function
13
47
14
- cacheSolve <- function (x , ... ) {
15
- # # Return a matrix that is the inverse of 'x'
48
+ test = function (mat ){
49
+ # # @mat: an invertible matrix
50
+
51
+ temp = makeCacheMatrix(mat )
52
+
53
+ start.time = Sys.time()
54
+ cacheSolve(temp )
55
+ dur = Sys.time() - start.time
56
+ print(dur )
57
+
58
+ start.time = Sys.time()
59
+ cacheSolve(temp )
60
+ dur = Sys.time() - start.time
61
+ print(dur )
16
62
}
63
+
0 commit comments