Skip to content

Commit 4dd62fa

Browse files
author
Rich Davies
committed
Solve assignment 2: caching inverted matrices.
1 parent 7f657dd commit 4dd62fa

File tree

1 file changed

+38
-8
lines changed

1 file changed

+38
-8
lines changed

cachematrix.R

Lines changed: 38 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,45 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## A utility for repeatedly accessing inverted matrices.
2+
## Computing a matrix's inverse is potentially expensive, so
3+
## this utility is optimized to avoid repeating the
4+
## computation by caching the results.
35

4-
## Write a short comment describing this function
5-
6-
makeCacheMatrix <- function(x = matrix()) {
6+
## Example:
7+
## > cm <- makeCacheMatrix(m) # construct an invertable matrix
8+
## > cacheSolve(cm) # computes and returns the inverse of m
9+
## > cacheSolve(cm) # returns the inverse of m, avoiding recomputation
10+
## > cm$set(m2) # changes the matrix, and clears the cache
11+
## > cacheSolve(cm) # computes and returns the inverse of m2
712

13+
## Construct a matrix that can be inversed multiple times.
14+
makeCacheMatrix <- function(original = matrix()) {
15+
cached_inverse <- NULL
16+
17+
# overrides the original matrix and clears the cached inverse
18+
set <- function(replacement) {
19+
original <<- replacement
20+
cached_inverse <<- NULL
21+
}
22+
23+
get <- function() original
24+
setInverse <- function(inverse) cached_inverse <<- inverse
25+
getInverse <- function() cached_inverse
26+
list(set = set, get = get,
27+
setInverse = setInverse,
28+
getInverse = getInverse)
829
}
930

1031

11-
## Write a short comment describing this function
12-
32+
## Efficiently access the inverse of a matrix constructed with makeCacheMatrix
1333
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
34+
cached <- x$getInverse()
35+
36+
if(!is.null(cached)) {
37+
message("cached:")
38+
return(cached)
39+
}
40+
41+
# else calculate, set and return inverse
42+
i <- solve(x$get(), ...)
43+
x$setInverse(i)
44+
i
1545
}

0 commit comments

Comments
 (0)