File tree Expand file tree Collapse file tree 1 file changed +46
-7
lines changed Expand file tree Collapse file tree 1 file changed +46
-7
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
3
-
4
- # # Write a short comment describing this function
1
+ # # Special wrapper of a matrix in cases where we need cheaper repeat access to the inverse.
5
2
3
+ # # Build the matrix wrapper
6
4
makeCacheMatrix <- function (x = matrix ()) {
5
+ # # by default we do not have an inverse.
6
+ inv <- NULL
7
7
8
+ # # Allow the caller to set a new matrix in place of the use used at initialisation.
9
+ set <- function ( y ) {
10
+ x <<- y
11
+ # # make sure an eventual cached inverse is cleared
12
+ inv <<- NULL
13
+ }
14
+
15
+ # # Return the matrix
16
+ get <- function () {
17
+ x
18
+ }
19
+
20
+ # # cache the inverse
21
+ setinverse <- function ( inverse ) {
22
+ inv <<- inverse
23
+ }
24
+
25
+ # # return the inverse
26
+ getinverse <- function () {
27
+ inv
28
+ }
8
29
}
9
30
10
31
11
- # # Write a short comment describing this function
12
-
32
+ # # Given an object returned by makeCacheMatrix, calculate the inverse and cache it for further calls.
33
+ # # If a cached inverse has already been calculated on the wrapped matrix, the cached version is returned.
13
34
cacheSolve <- function (x , ... ) {
14
35
# # Return a matrix that is the inverse of 'x'
15
- }
36
+
37
+ inv <- x $ getinverse
38
+
39
+ if ( ! is.null( inv ) ) {
40
+ # # The wrapped matrix has a non NULL inverse
41
+ message( " cache hit" )
42
+ return inv
43
+ }
44
+
45
+ # # Calculate the inverse using solve
46
+ # # TODO: handle special cases more carefully, not all matrices can be inverted.
47
+ inv <- solve( x $ get() )
48
+
49
+ # # Cache the result of solve()
50
+ x $ setinverse( inv )
51
+
52
+ # # return the inverse
53
+ inv
54
+ }
You can’t perform that action at this time.
0 commit comments