forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
88 lines (70 loc) · 2.59 KB
/
cachematrix.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
## matrix inversion caching exercise
## Create matrix interface, instantiating getters & setters
makeCacheMatrix <- function(x = matrix()) {
# Clear out the inverse
inverse <- NULL
# Facility to allow changing the vector after the fact
set <- function(y) {
x <<- y
inverse <<- NULL
}
# Return the matrix itself.
get <- function() x
# Accept a value (any value) and assign it to variable inverse
setInverse <- function(value) inverse <<- value
# Return the inverse variable
getInverse <- function() inverse
return(
list(
set=set,
get=get,
getInverse=getInverse,
setInverse=setInverse
)
)
}
## Returns cached inverse matrix, or calculate it if no cache present
cacheSolve <- function(x, ...) {
inverse <- x$getInverse()
# check for cached inverse
if(!is.null(inverse)) {
message("retrieving cached matrix")
return(inverse)
}
# get the matrix, find and set the inverse and return the result.
matrix <- x$get()
inverse <- solve(matrix)
x$setInverse(inverse)
return(inverse)
}
## Walk through proof of work
checkWork <- function() {
# Creates matrix to work with
checkMatrix <- makeCacheMatrix(matrix(rnorm(25),5,5))
message("here's our brand new matrix!")
print(checkMatrix$get())
# Creates a bogus 'inverse'
bogusInverse <- matrix(rep(1,25),5,5)
message("let's create a bogus inverse matrix and assign it using setInverse")
print(bogusInverse)
checkMatrix$setInverse(bogusInverse)
# Test that getInverse returns our bogus inverse matrix
message("let's use getInverse() and verify it returns the bogus inverse")
print(checkMatrix$getInverse())
# Test that cacheSolve returns the 'cached' bogus inverse matrix
message("...and that calling cacheSolve() happily returns the 'cached' bogus inverse as well")
print(cacheSolve(checkMatrix))
# Let's recreate a fresh matrix
message("now let's create a shiny new matrix")
checkMatrix <- makeCacheMatrix(matrix(rnorm(25),5,5))
print(checkMatrix$get())
# Let's compute the inverse
message("for which we'll compute the inverse")
print(inverse <- cacheSolve(checkMatrix))
# Run again and see if we see "retrieving cached matrix" message
message("let's see if we get the 'retrieving cached matrix' message when we rerun cacheSolve")
print(inverse <- cacheSolve(checkMatrix))
# Now we'll check that it multiplying it by the original matrix gives us the identity matrix
message("now we'll check that we actually have the inverse. \nmultiplying the two should give us an identity matrix...")
round(inverse %*% checkMatrix$get())
}