forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachematrix.R
69 lines (51 loc) · 1.99 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
## Matrix inversion is usually a costly computation and there
## are benefits to cache the inverse of a matrix
## rather than computing it repeatedly. The two functions below
## cache the inverse of a matrix.
## The function creates a special "matrix" object that can cache
## its inverse.
makeCacheMatrix <- function(x = matrix()) {
# initialize the stored value of the inverse to null
inverse <- NULL
# set the value of the matrix
set <- function(y) {
x <<- y
# re-initialize the stored value of inverse
# to null because the function changed
inverse <<- NULL
}
#get the value of the matrix
get <- function() { x }
# set the inverse of the matrix
setinverse <- function(i) { inverse <<- i }
# get the inverse of the matrix
getinverse <- function() { inverse }
## returns a list of 4 functions above
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## The function computes the inverse of the
## special "matrix" returned by makeCacheMatrix above.
## If the inverse has already been calculated (and the
## matrix has not changed), then cacheSolve should retrieve
## the inverse from the cache.
cacheSolve <- function(x, ...) {
# get the cached inverse; could be null
inverse <- x$getinverse()
# if inverse is cached, get the cached value,
# and return
if(!is.null(inverse)) {
message("getting cached data")
return(inverse)
}
# if inverse is not cached, get value of matrix
data <- x$get()
# then compute its inverse
inverse <- solve(data, ...)
# then set the cached value of the inverse
x$setinverse(inverse)
# and then return the inverse matrix
inverse
}