1
- # # Put comments here that give an overall description of what your
2
- # # functions do
1
+ # # makeCacheMatrix and cacheSolve are used to create an object-like list
2
+ # # for a square invertible matrix and then solve for the inverse of that matrix.
3
+ # # The inverse is cached for later use to speed up program execution.
3
4
4
- # # Write a short comment describing this function
5
+ # # The makeCacheMatrix function takes a matrix as input and returns a list of
6
+ # # functions to:
7
+ # # 1. set the value of the matrix
8
+ # # 2. get the value of the matrix
9
+ # # 3. set the value of the inverse of the matrix (and cache the value)
10
+ # # 4. get the value of the inverse of the matrix
11
+ # # Note: The matrix is assumed to be a square invertible matrix.
5
12
6
13
makeCacheMatrix <- function (x = matrix ()) {
7
-
14
+ m <- NULL
15
+ set <- function (y ) {
16
+ x <<- y
17
+ m <<- NULL
18
+ }
19
+ get <- function () x
20
+ setinverse <- function (inverse ) m <<- inverse
21
+ getinverse <- function () m
22
+ list (set = set , get = get ,
23
+ setinverse = setinverse ,
24
+ getinverse = getinverse )
8
25
}
9
26
10
-
11
- # # Write a short comment describing this function
27
+ # # The cacheSolve function calculates the inverse of a "makeCacheMatrix" matrix
28
+ # # as created above. If this value has already been cached, cacheSolve simply
29
+ # # returns the value without having to do any further resource draining calculations.
12
30
13
31
cacheSolve <- function (x , ... ) {
14
- # # Return a matrix that is the inverse of 'x'
32
+ # # Return a matrix that is the inverse of 'x'
33
+ m <- x $ getinverse()
34
+ if (! is.null(m )) {
35
+ message(" getting cached data" )
36
+ return (m )
37
+ }
38
+ data <- x $ get()
39
+ m <- solve(data , ... )
40
+ x $ setinverse(m )
41
+ m
15
42
}
43
+
44
+ # # Below is just some example code that can be used to test the above functions.
45
+
46
+ # test <- matrix(rnorm(9), 3, 3)
47
+ # test
48
+ # expected <- solve(test)
49
+
50
+ # cachetest <- makeCacheMatrix(test)
51
+ # cachesolvetest <- cacheSolve(cachetest)
52
+
53
+ # cachesolvetest == expected
54
+
55
+ # cachesolvetest <- cacheSolve(cachetest)
56
+
57
+ # # This output shows that the cached value is properly retrieved:
58
+ # # > cachesolvetest2 <- cacheSolve(cachetest)
59
+ # # getting cached data
60
+
61
+ # cachesolvetest == cachesolvetest2 & cachesolvetest2 == expected
62
+
63
+ # # All the calculated inverses are logically equivalent as expected:
64
+ # # [,1] [,2] [,3]
65
+ # # [1,] TRUE TRUE TRUE
66
+ # # [2,] TRUE TRUE TRUE
67
+ # # [3,] TRUE TRUE TRUE
0 commit comments