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
51 lines (47 loc) · 1.34 KB
/
cachematrix.R
File metadata and controls
51 lines (47 loc) · 1.34 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
## Cache a matrix inverse.
## Example:
## > mtx <- makeCacheMatrix(matrix(1:4,2,2))
## > cacheSolve(mtx)
## [,1] [,2]
## [1,] -2 1.5
## [2,] 1 -0.5
## > cacheSolve(mtx)
## getting cached data
## [,1] [,2]
## [1,] -2 1.5
## [2,] 1 -0.5
## function makeCacheMatrix
## Create an object that encapsulates a matrix and caches the inverse of it.
## Used in conjunction with cacheSolve
## Arguments:
## x: A matrix that has an inverse
makeCacheMatrix <- function(x = matrix()) {
inverse <- NULL
set <- function(y) {
x <<- y
inverse <<- NULL
}
get <- function() x
setInverse <- function(inv) inverse <<- inv
getInverse <- function() inverse
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## function cacheSolve
## Solve the inverse of a matrix, encapsuled by makeCacheMatrix.
## If the function is called repeatedly for the same cached matrix,
## then the cached inverse is returned rather than being recalculated.
## Arguments:
## x: an encapsuled matrix, created by makeCacheMatrix.
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
}