forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
53 lines (38 loc) · 1.5 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
## Factory creates a list object containing getter and setter functions
## for saveing and retrieving a matrix and its inverse in assocated working environment.
makeCacheMatrix <- function(cachedData = matrix()) {
cachedInverse <- NULL
set <- function(data) {
cachedData <<- data
cachedInverse <<- NULL
}
get <- function() cachedData
setInverse <- function(inverse) cachedInverse <<- inverse
getInverse <- function() cachedInverse
list(set = set,
get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## Returns the inverse of a matrix assocated with the working env of makeCacheMatrix instance.
## The inverse is calculated once the first time the function is called,
## subsequent calles return the cached inverse.
cacheSolve <- function(funcList, ...) {
## Return a matrix that is the inverse of 'x'
inverse <- funcList$getInverse()
if(!is.null(inverse)) {
message("getting cached data")
return(inverse)
}
inverse <- solve(funcList$get(), ...)
funcList$setInverse(inverse)
inverse
}
## Some test code
data<-matrix(c(1,2,3,4),nrow=2,ncol=2)
mv<-makeCacheMatrix()
mv$set(data)
cacheSolve(mv)
mv$get()
mv$getInverse()%*%mv$get() ## should return diagonal maxtrix
cacheSolve(mv)%*%mv$get() ## should return diagonal maxtrix