|
1 | 1 | ## Put comments here that give an overall description of what your
|
2 | 2 | ## functions do
|
3 |
| - |
| 3 | +## makeCacheMatrix and cacheSolve can be used together to calculate the inverse |
| 4 | +## of a matrix and cache the result such that the inverse only has to be |
| 5 | +## calculated once. |
4 | 6 | ## Write a short comment describing this function
|
5 |
| - |
| 7 | +## makeCacheMatrix creates a list that provides functionality to get and set |
| 8 | +## the cached value of calculating the inverse of a matrix |
6 | 9 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 10 | + inverse <- NULL |
| 11 | + set <- function(new.x) { |
| 12 | + x <<- new.x |
| 13 | + inverse <<- NULL |
| 14 | + } |
| 15 | + get <- function() { x } |
| 16 | + set.inverse <- function(new.inverse) { inverse <<- new.inverse } |
| 17 | + get.inverse <- function() { inverse } |
| 18 | + list(set = set, get = get, |
| 19 | + set.inverse = set.inverse, |
| 20 | + get.inverse = get.inverse) |
8 | 21 | }
|
9 | 22 |
|
10 | 23 |
|
11 | 24 | ## Write a short comment describing this function
|
12 |
| - |
| 25 | +## cacheSolve when given a list such as created by the makeCacheMatrix function |
| 26 | +## can calculate the inverse of the matrix and cache the result such that it |
| 27 | +## only has to be calculated once. |
13 | 28 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 29 | + ## Return a matrix that is the inverse of 'x' |
| 30 | + inverse <- x$get.inverse() |
| 31 | + if (!is.null(inverse)) { |
| 32 | + message("getting cached data") |
| 33 | + return(inverse) |
| 34 | + } |
| 35 | + data <- x$get() |
| 36 | + inverse <- solve(data, ...) |
| 37 | + x$set.inverse(inverse) |
| 38 | + inverse |
15 | 39 | }
|
0 commit comments