File tree Expand file tree Collapse file tree 1 file changed +33
-4
lines changed Expand file tree Collapse file tree 1 file changed +33
-4
lines changed Original file line number Diff line number Diff line change 1
- # # Put comments here that give an overall description of what your
2
- # # functions do
1
+ # # These functions implement an object in R representing a matrix with the
2
+ # # ability to cache its own inverse when using the cacheSolve function.
3
3
4
- # # Write a short comment describing this function
4
+ # # makeCacheMatrix makes an R object to cache the inverse for a given matrix
5
5
6
6
makeCacheMatrix <- function (x = matrix ()) {
7
+ # initially we do not know the inverse
8
+ i <- NULL
7
9
10
+ # define the functions this object implements
11
+ set <- function (y ) {
12
+ x <<- y
13
+ # must reset cached inverse when x changes
14
+ i <<- NULL
15
+ }
16
+ get <- function () x
17
+ setinverse <- function (inverse ) i <<- inverse
18
+ getinverse <- function () i
19
+
20
+ # return the object as a list
21
+ list (set = set , get = get ,
22
+ setinverse = setinverse ,
23
+ getinverse = getinverse )
8
24
}
9
25
10
26
11
- # # Write a short comment describing this function
27
+ # # cacheSolve solves the inverse for the matrix object, unless it is cached
12
28
13
29
cacheSolve <- function (x , ... ) {
30
+ # if it is cached, then just return it
31
+ i <- x $ getinverse()
32
+ if (! is.null(i )) {
33
+ # for debugging: message("getting cached data")
34
+ return (i )
35
+ }
36
+
37
+ # otherwise, solve and cache it for future use
38
+ data <- x $ get()
39
+ i <- solve(data , ... )
40
+ x $ setinverse(i )
41
+
14
42
# # Return a matrix that is the inverse of 'x'
43
+ i
15
44
}
You can’t perform that action at this time.
0 commit comments