forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachematrix.R
53 lines (41 loc) · 1.48 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
## The following functions allow the creation of matrices caching their own inverse.
## Once constructed such a matrix via the 'makeCacheMatrix' function,
## use 'cacheSolve' to compute the matix' inverse. If the inverse has been computed
## previously, the cached inverse is merely returned, unless the matrix was changed
## meanwhile.
# Constructs matrix which caches its own inverse.
# Argument x denotes the initial matrix that should be
# turned into a cached variant.
makeCacheMatrix <- function(x = matrix()) {
inverse <- NULL
# sets new matrix and clears cache
set <- function(y) {
x <<- y
inverse <<- NULL
}
# gets matrix and get/set inverse
get <- function() x
setinverse <- function(i) inverse <<- i
getinverse <- function() inverse
# return cached matrix as list of functions
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
# Computes inverse of cached matrix. If the inverse
# has been computed previously, the cached version of
# the inverse is returned
cacheSolve <- function(x, ...) {
inverse <- x$getinverse()
# if the inverse has already been computed
if(!is.null(inverse)) {
message("getting cached matrix")
return(inverse)
}
# get matrix and actually compute inverse
data <- x$get()
inverse <- solve(data, ...)
# cache inverse and return it
x$setinverse(inverse)
inverse
}