forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachematrix.R
51 lines (42 loc) · 1.2 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
## makeCacheMatrix creates a special "matrix" object that can cache its inverse
## Note: Does NOT check if matrix is invertible
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
## set matrix to be inverted
setMatrix <- function(y) {
x <<- y
m <<- NULL
}
#get matrix to be inverted
getMatrix <- function() {
x
}
#set inverse of matrix
setInverse <- function(inv) {
m <<- inv
}
## get inverse of matrix
getInverse <- function() {
m
}
list(setMatrix = setMatrix, getMatrix = getMatrix,
setInverse = setInverse,
getInverse = getInverse
)
}
## cacheSolve computes the inverse of the "matrix" returned by makeCacheMatrix
## If inverse is already calculated then cacheSolve will retrieve from cache.
cacheSolve <- function(x, ...) {
## If inverse matrix already stored in cache
## then return it
m <- x$getInverse()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
## if inverse matrix does NOT exist in cache
## then compute, store, and return it.
m <- solve(x$getMatrix(), ...)
x$setInverse(m)
m
}