Skip to content

Commit b58f543

Browse files
committed
Implement the cachematrix helper methods (and document them)
1 parent 7f657dd commit b58f543

File tree

1 file changed

+60
-7
lines changed

1 file changed

+60
-7
lines changed

cachematrix.R

Lines changed: 60 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,68 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
# ------------------------------------------------------------------------------
2+
# Helper functions to compute and cache the inverse of a matrix (i.e. "solve" a
3+
# matrix).
4+
#
5+
# Note: we assume a square matrix (i.e. one that is invertible) is always
6+
# provided when using these functions. Therefore there is no erro handling for
7+
# cases where this is not true.
8+
#-------------------------------------------------------------------------------
39

4-
## Write a short comment describing this function
510

11+
# Given an initial matrix, this method returns a special wrapper, in the form of
12+
# a list with functions that can be used to:
13+
# - set the underlying matrix again
14+
# - get the underlying matrix
15+
# - set the inverse of the underlying matrix
16+
# - get th inverse of the underlying matrix
617
makeCacheMatrix <- function(x = matrix()) {
7-
18+
i <- NULL # Cache value for the inverse matrix of `x`
19+
20+
# Setter method, if we want to overwrite the underlying matrix `x`
21+
set <- function(y) {
22+
x <<- y
23+
i <<- NULL
24+
}
25+
26+
# Getter method, to access the underlying matrix `x`
27+
get <- function() {
28+
x
29+
}
30+
31+
# Set the inverse of the underlying matrix `x`, into the cache
32+
setinverse <- function(inverse) {
33+
i <<- inverse
34+
}
35+
36+
# Get the inverse of the underlying matrix `x`, from the cache
37+
# Note: this will return `NULL` if the cache hasn't been set yet
38+
getinverse <- function() {
39+
i
40+
}
41+
42+
list(set = set, get = get,
43+
setinverse = setinverse,
44+
getinverse = getinverse)
845
}
946

1047

11-
## Write a short comment describing this function
12-
48+
# Use this method to "solve" (i.e. get the inverse) of a matrix, doing so in a
49+
# way that caches the very first computation of the inverse and uses the cache
50+
# subsequently.
51+
#
52+
# The argument `x` MUST be the special wrapper obtained from `makeCacheMatrix`.
1353
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
54+
## Return a matrix that is the inverse of 'x'
55+
56+
# Try to get the cached value
57+
i <- x$getinverse()
58+
if(!is.null(i)) {
59+
message("getting cached data")
60+
return(i)
61+
}
62+
63+
# … otherwise compute the inverse and cache
64+
data <- x$get()
65+
i <- solve(data, ...)
66+
x$setinverse(i)
67+
i
1568
}

0 commit comments

Comments
 (0)