forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachematrix.R
84 lines (73 loc) · 1.91 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
##
# written by [email protected]
#
## cacheSolve()
# returns the inverse of a makeCacheMatrix object.
#
# side effect: will cause inv to be calculated if it does not already exist
#
# use the test() to see if code works
# If the code works you should see a matrix, all the values should be true
#
#
# makeCacheMatrix returns an object that is similar to a java POJO
#
# To Create an object
# myVar <- makeCacheMatrix(x)
#
# Here is an example of how to call the accessor functions stored in the objects list
# myCM$get()
#
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL #inverse of maxtrix x
# replace the matrix data member we are caching
set <- function(y) {
x <<- y
inv <<- NULL
}
# return the matix pass as 'constructor' arg
get <- function() {
x
}
setInverse <- function(inverse) {
inv <<- inverse
}
getInverse <- function() {
inv
}
# This list contains all of our "member functions"
list(set = set, get = get,
getInverse = getInverse,
setInverse = setInverse)
}
#
# returns the inverse of makeCacheMatrix object
#
# checks to see if inverse value has already been stored in the makeCacheMatrix
# if not, it calculates the inverse and saves it in the makeCacheMatrix object
#
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getInverse()
if (!is.null(inv)) {
message("getting cached data")
return(m)
}
data <- x$get()
inv <-solve(data)
x$setInverse(inv)
inv
}
#
# test()
# will return true if we are able to correctly calculate the inverse of a small matrix
#
test <- function() {
m <- matrix(1:4, 2, 2)
mcm <- makeCacheMatrix(m)
cs <- cacheSolve(mcm)
inv <- mcm$getInverse()
expectedData <- list(-2, 1, 1.5, -0.5)
expectedMatrix <- matrix(expectedData, 2, 2)
inv == expectedMatrix
}