|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## Functions for creating an object that stores a matrix and its inverse, when calculated. |
| 2 | +## When the matrix is changed, the inverse cache is nullified. |
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
| 4 | +## Creates a wrapping object around a matrix that can store a cache of its inverse |
5 | 5 |
|
6 | 6 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 7 | + inv <- NULL # contains the cached inverse |
| 8 | + set <- function(y) { # sets a new value and nullifies the inverse cache |
| 9 | + x <<- y |
| 10 | + inv <<- NULL |
| 11 | + } |
| 12 | + get <- function() x # retrieves the matrix |
| 13 | + setinverse <- function(inverse) inv <<- inverse # sets the inverse cache |
| 14 | + getinverse <- function() inv # retrieves the cached inverse |
| 15 | + list(set=set, get=get, setinverse=setinverse, getinverse=getinverse) |
8 | 16 | }
|
9 | 17 |
|
10 | 18 |
|
11 |
| -## Write a short comment describing this function |
| 19 | +## Tries to retrieve the inverse matrix of an object created by makeCacheMatrix, |
| 20 | +## and calculates it if necessary |
12 | 21 |
|
13 | 22 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 23 | + inv <- x$getinverse() |
| 24 | + if(!is.null(inv)) { |
| 25 | + # the inverse is already known; no need to recalculate |
| 26 | + message("getting cached data") |
| 27 | + return(inv) |
| 28 | + } |
| 29 | + data <- x$get() |
| 30 | + inv <- solve(data, ...) # calculates the inverse matrix |
| 31 | + x$setinverse(inv) # caches the inverse matrix for future use |
| 32 | + inv |
15 | 33 | }
|
0 commit comments