File tree Expand file tree Collapse file tree 1 file changed +37
-3
lines changed Expand file tree Collapse file tree 1 file changed +37
-3
lines changed Original file line number Diff line number Diff line change 4
4
# # Write a short comment describing this function
5
5
6
6
makeCacheMatrix <- function (x = matrix ()) {
7
-
7
+ # first make a local variable `im` for the inverse matrx
8
+ im <- NULL
9
+ # enable setting of global env variables
10
+ set <- function (y ) {
11
+ # # scope matrix to a global env variable `x`
12
+ x <<- y
13
+ # # scope an empty global env variable `im`
14
+ im <<- NULL
15
+ }
16
+ # # return original matrix
17
+ get <- function () {x }
18
+ # # Set `im` to be calculated inversematrix in global environment lexical scope by using `<<-`
19
+ setinverse <- function (inversematrix ) {
20
+ im <<- inversematrix
21
+ }
22
+ # retrieve the inverse matrix of x
23
+ getinverse <- function () {im }
24
+ list (set = set , get = get , setinverse = setinverse , getinverse = getinverse )
8
25
}
9
26
10
27
11
28
# # Write a short comment describing this function
29
+ # # assume matrix `x` is always invertable
12
30
13
31
cacheSolve <- function (x , ... ) {
14
- # # Return a matrix that is the inverse of 'x'
15
- }
32
+ # # Return a matrix that is the inverse of 'x'
33
+ # `x` is a matrix
34
+ # `ix` is inverse of matrix
35
+
36
+ # `x` is makeCacheMatrix object
37
+ ix <- x $ getinverse()
38
+ if (! is.null(ix )) {
39
+ message(" getting cached data" )
40
+ return (ix )
41
+ }
42
+
43
+ # # inverse the matrix
44
+ message(" calculating inverse and caching result" )
45
+ matrix <- x $ get()
46
+ ix <- solve(matrix , ... )
47
+ x $ setinverse(ix )
48
+ ix
49
+ }
You can’t perform that action at this time.
0 commit comments