|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## These functions take the sometimes time-consuming task of |
| 2 | +## calculating the inverse of a matrix, and ensure that while |
| 3 | +## the underlying matrix remains unchanged, the calculation |
| 4 | +## of the inverse need only happen once. |
3 | 5 |
|
4 |
| -## Write a short comment describing this function |
| 6 | +## This function takes a matrix as an argument, and contains |
| 7 | +## getters and setters for both the matrix itself, and the |
| 8 | +## inverse of the matrix. |
5 | 9 |
|
6 | 10 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 11 | + inverse <- NULL |
| 12 | + set <- function(y) { |
| 13 | + x <<- y |
| 14 | + inverse <<- NULL |
| 15 | + } |
| 16 | + get <- function() { |
| 17 | + x |
| 18 | + } |
| 19 | + setInverse <- function(invertedMatrix) { |
| 20 | + inverse <<- invertedMatrix |
| 21 | + } |
| 22 | + getInverse <- function() { |
| 23 | + inverse |
| 24 | + } |
| 25 | + list(set = set, get = get, |
| 26 | + setInverse = setInverse, |
| 27 | + getInverse = getInverse) |
8 | 28 | }
|
9 | 29 |
|
10 | 30 |
|
11 |
| -## Write a short comment describing this function |
| 31 | +## This function takes an object created with makeCacheMatrix |
| 32 | +## as an argument and returns the inverse of its matrix, from |
| 33 | +## cache if it exists, and via calculation that is then cached |
| 34 | +## if not. |
12 | 35 |
|
13 | 36 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 37 | + ## Return a matrix that is the inverse of 'x' |
| 38 | + invertedMatrix <- x$getInverse() |
| 39 | + if(!is.null(invertedMatrix)) { |
| 40 | + message("getting cached data") |
| 41 | + return(invertedMatrix) |
| 42 | + } |
| 43 | + data <- x$get() |
| 44 | + invertedMatrix <- solve(data) |
| 45 | + x$setInverse(invertedMatrix) |
| 46 | + invertedMatrix |
15 | 47 | }
|
0 commit comments