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
102 lines (85 loc) · 2.23 KB
/
cachematrix.R
File metadata and controls
102 lines (85 loc) · 2.23 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# Functions for caching the inverse of a matrix with it.
makeCacheMatrix <- function(x = matrix()) {
# Create a Matrix object (an R list in fact) that encapsulates a matrix
# and provides methods to set() and get() the orginal matrix and
# to setInverse() and getInverse() its inverse, to cache it.
#
# Args:
# x: The matrix to encapsulate.
#
# Returns:
# The cached matrix object.
# The cached inverse of the matrix.
inverseOfMatrix <- NULL
set <- function(original) {
# Set, i.e. preserve, the original matrix;
# and clear its, perhaps previously cached, inverse.
#
# Args:
# original: The original matrix to be preserved.
#
# Retuns:
# NULL
x <<- original
inverseOfMatrix <<- NULL
}
get <- function() {
# Get the orginal matrix.
#
# Args:
#
# Retuns:
# The original matrix.
x
}
setInverse <- function(inverse) {
# Set, i.e. preserve, the inverse of the matrix.
#
# Args:
# inverse: The inverse of the matrix to be cached.
#
# Retuns:
# The inverse.
inverseOfMatrix <<- inverse
}
getInverse <- function() {
# Get the inverse of the matrix
#
# Args:
#
# Retuns:
# The inverse.
inverseOfMatrix
}
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
}
cacheSolve <- function(x, ...) {
# Compute the inverse of the special "matrix" returned by makeCacheMatrix above.
# If the inverse has already been calculated (and the matrix has not changed),
# then get the inverse from the cache.
#
# Args:
# x: The matrix to invert and cache.
# ...: additional argumenst are passed to solve()
#
# Returns:
# The, perhaps previously cached, inverse.
inverse <- x$getInverse()
if (is.null(inverse)) {
message("Patience, calculating inverse ...")
original <- x$get()
inverse <- solve(original, ...)
x$setInverse(inverse)
}
inverse
}
## Test
# m <- matrix(data = c(0, 1, 1, 0), nrow = 2, ncol = 2)
# mc <- makeCacheMatrix(m)
# cacheSolve(mc)
## Patience, calculating inverse ...
## ... inverse matrix
# cacheSolve(mc)
## ... inverse matrix
# identical(mc$get(), mc$getInverse())
## [1] TRUE