File tree Expand file tree Collapse file tree 1 file changed +46
-9
lines changed Expand file tree Collapse file tree 1 file changed +46
-9
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
+ # # A pair of functions that cache the inverse of a matrix.
5
2
3
+ # # This function creates a special "matrix" object that can cache its inverse.
6
4
makeCacheMatrix <- function (x = matrix ()) {
7
-
5
+ # the inverse of the matrix
6
+ inverse <- NULL
7
+
8
+ # set the matrix
9
+ set <- function (newMatrix ) {
10
+ x <<- newMatrix
11
+ x <<- NULL
12
+ }
13
+
14
+ # get the matrix
15
+ get <- function () {
16
+ x
17
+ }
18
+
19
+ # set the inverse
20
+ setInverse <- function (inv ) {
21
+ inverse <<- inv
22
+ }
23
+
24
+ # get the inverse
25
+ getInverse <- function () {
26
+ inverse
27
+ }
28
+
29
+ # return special "matrix" object
30
+ list (set = set , get = get , setInverse = setInverse , getInverse = getInverse )
8
31
}
9
32
10
-
11
- # # Write a short comment describing this function
12
-
33
+ # # This function computes the inverse of the special "matrix" returned by makeCacheMatrix above.
13
34
cacheSolve <- function (x , ... ) {
14
- # # Return a matrix that is the inverse of 'x'
35
+ # get cached value of matrix inverse
36
+ inverse <- x $ getInverse()
37
+
38
+ # if it's not null, return it
39
+ if (! is.null(inverse )) {
40
+ message(" getting cached inverse" )
41
+ return (inverse )
42
+ }
43
+
44
+ # otherwise we need to calculate it
45
+ inverse <- solve(x $ get())
46
+
47
+ # then cache it
48
+ x $ setInverse(inverse )
49
+
50
+ # return the inverse
51
+ inverse
15
52
}
You can’t perform that action at this time.
0 commit comments