|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 |
| - |
4 |
| -## Write a short comment describing this function |
| 1 | +## Create a special object that stores a matrix, and caches |
| 2 | +## its inverse. |
5 | 3 |
|
| 4 | +## This function creates an object that provides functions for storing |
| 5 | +## and retrieving a matrix (set, get), as well as storing and retrieving |
| 6 | +## the matrix's inverse (setinverse, getinverse). |
6 | 7 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 8 | + inv <- NULL |
| 9 | + set <- function(y) { |
| 10 | + x <<- y |
| 11 | + inv <<- NULL ## reset the inverse to null |
| 12 | + } |
| 13 | + get <- function() x |
| 14 | + setinverse <- function(inverse) inv <<- inverse |
| 15 | + getinverse <- function() inv |
| 16 | + list(set = set, get = get, |
| 17 | + setinverse = setinverse, |
| 18 | + getinverse = getinverse) |
8 | 19 | }
|
9 | 20 |
|
10 | 21 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 22 | +## This function return a matrix that is the inverse of the matrix |
| 23 | +## stored in x. |
| 24 | +## - If there is a cached value, then that value is returned. |
| 25 | +## - If a cached value does not exist, then the function calculates |
| 26 | +## the inverse, caches it, and returns that value. |
13 | 27 | cacheSolve <- function(x, ...) {
|
14 | 28 | ## Return a matrix that is the inverse of 'x'
|
| 29 | + inv <- x$getinverse() |
| 30 | + if(!is.null(inv)) { |
| 31 | + message("getting cached data") |
| 32 | + return(inv) |
| 33 | + } |
| 34 | + data <- x$get() |
| 35 | + inv <- solve(data) |
| 36 | + x$setinverse(inv) |
| 37 | + inv |
15 | 38 | }
|
0 commit comments