1
1
# Getting the inverse of a matrix in R is simple, but it may be computationally
2
2
# expensive. If we have a suitable square matrix, one line of R code will
3
- # do the job, but if we may need to compute the same inverse many times,in a loop
4
- # for example, it may be useful to cache the inverse. The two functions makeCacheMatrix()
3
+ # do the job, but if we may need to compute the same inverse many times, it may be useful
4
+ # to cache the inverse.
5
+ # The two functions makeCacheMatrix()
5
6
# and cacheSolve() work together to cache a the matrix and its inverse so that the computation
6
- # only needs to be done once. See individual functions for implementation details.
7
+ # only needs to be done once. See individual functions for implementation details and a
8
+ # transcript of their use at the end of this file.
7
9
8
10
# # makeCacheMatrix
9
- # initialize a matrix and an intial value of its inverse. The matix may be empty.
10
- # the inverse will be null
11
-
12
- # include functions to get/set matrix and get/set its inverse
13
-
11
+ # Initialize a matrix and an intial value of its inverse. The matix may be empty.
12
+ # tThe inverse will be null
13
+ # dDefine functions to get/set matrix and get/set its inverse
14
+ # The return value will be a list of data and functions.
15
+ # Taken together these functions and data use R's functional features
16
+ # to create an 'object'
14
17
makeCacheMatrix <- function (x = matrix ()) {
15
18
i <- NULL
16
19
set <- function (y ) {
@@ -25,17 +28,17 @@ makeCacheMatrix <- function(x = matrix()) {
25
28
getInverse = getInverse )
26
29
}
27
30
# # cacheSolve
28
- # get the inverse of the cached matrix
29
- # if it is NULL, compute the inverse
30
- # if it is not NULL, return the cached value
31
+ # Get the inverse of the cached matrix
32
+ # If it is NULL, compute the inverse
33
+ # If it is not NULL, return the cached value
31
34
cacheSolve <- function (x , ... ) {
32
35
i <- x $ getInverse()
33
36
if (! is.null(i )) { # if the inverse is not NULL, use cached value
34
37
message(" getting cached data" )
35
38
return (i )
36
39
}
37
- data <- x $ get() # the inverse was NULL. Get the matrix
38
- i <- solve(data ) # recompute matrix inverse
39
- x $ setInverse(i ) # cache the inverse
40
- i # return the inverse
40
+ data <- x $ get() # the inverse was NULL. Get the matrix
41
+ i <- solve(data ) # recompute matrix inverse
42
+ x $ setInverse(i ) # cache the inverse
43
+ i # return the inverse
41
44
}
0 commit comments