|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 |
| - |
4 |
| -## Write a short comment describing this function |
5 |
| - |
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 1 | +# An instance of makeCacheMatrix can be initialised by passing a |
| 2 | +# square matrix as an argument. The created instance can then be |
| 3 | +# passed to cacheSolve, which will invert the matrix, cache and |
| 4 | +# return the result. Subsequent calls to cacheSolve with the |
| 5 | +# same makeCacheMatrix instance will return the cached result |
| 6 | +# and not invert the matrix again. |
7 | 7 |
|
| 8 | +# Allows caching of a matrix and its inverse value |
| 9 | +makeCacheMatrix <- function(matrix = matrix()) { |
| 10 | + inverseMatrix <- NULL |
| 11 | + |
| 12 | + # Caches a matrix and clears the inverse cache |
| 13 | + set <- function(newMatrix) { |
| 14 | + matrix <<- newMatrix |
| 15 | + inverseMatrix <<- NULL |
| 16 | + } |
| 17 | + |
| 18 | + # Gets the original unsolved matrix |
| 19 | + get <- function() matrix |
| 20 | + |
| 21 | + # Caches a solved matrix |
| 22 | + setInverse <- function(inverse) inverseMatrix <<- inverse |
| 23 | + |
| 24 | + # Gets the solved matrix |
| 25 | + getInverse <- function() inverseMatrix |
| 26 | + |
| 27 | + list( |
| 28 | + set = set, |
| 29 | + get = get, |
| 30 | + setInverse = setInverse, |
| 31 | + getInverse = getInverse |
| 32 | + ) |
8 | 33 | }
|
9 | 34 |
|
10 | 35 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 36 | +# Takes an initialised instance of makeCacheMatrix |
| 37 | +# and solves or accesses the cached matrix within it |
| 38 | +cacheSolve <- function(matrixCacher, ...) { |
| 39 | + inverseMatrix <- matrixCacher$getInverse() |
| 40 | + |
| 41 | + # Check if the cached original matrix has been solved already |
| 42 | + if(!is.null(inverseMatrix)) { |
| 43 | + return(inverseMatrix) |
| 44 | + } |
| 45 | + |
| 46 | + # Get the original matrix |
| 47 | + matrix <- matrixCacher$get() |
| 48 | + |
| 49 | + # Solve the original matrix |
| 50 | + inverseMatrix <- solve(matrix) |
| 51 | + |
| 52 | + # Store the newly solved matrix |
| 53 | + matrixCacher$setInverse(inverseMatrix) |
| 54 | + |
| 55 | + # Return the newly solved matrix |
| 56 | + inverseMatrix |
15 | 57 | }
|
0 commit comments