forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
53 lines (34 loc) · 1.19 KB
/
cachematrix.R
File metadata and controls
53 lines (34 loc) · 1.19 KB
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
## With these two functions we enable a matrix to cache its own inverse for performance reasons
## Special thanks to rdpeng for his outstanding stub files.
## Function takes a matrix and returns a special "matrix" object that can get and set its inverse by cache
makeCacheMatrix <- function(x = matrix()) {
inverse <- NULL
set <- function(y) {
x <<- y
inverse <<- NULL
}
get <- function() {
x
}
setInverse <- function(newInverse) {
inverse <<- newInverse
}
getInverse <- function() {
inverse
}
list(get=get, set=set, getInverse=getInverse, setInverse=setInverse)
}
## Function takes a special "matrix" object returned from makeCacheMatrix,
## returns the inverse of the matrix either by fetching from cache if available or calculating it anew
## if the inverse was newly calculated it is cached for future use.
cacheSolve <- function(x, ...) {
inverse <- x$getInverse()
if(!is.null(inverse)) {
message("getting cached data")
return(inverse)
}
data <- x$get()
inverse <- solve(data)
x$setInverse(inverse)
inverse
}