|
1 | 1 | ## Put comments here that give an overall description of what your
|
2 | 2 | ## functions do
|
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
5 |
| - |
| 4 | +## makeCacheMatrix creates a special "matrix", which is really a list containing a function which |
| 5 | +## 0. Checks we have a square matrix |
| 6 | +## 1. set the value of the matrix |
| 7 | +## 2. get the value of the matrix |
| 8 | +## 3. set the value of the matrix inverse |
| 9 | +## 4. get the value of the matrix inverse |
6 | 10 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 11 | + |
| 12 | + ## Validation you can only inverse a square matrix using solve() |
| 13 | + ## Check we have a square matrix |
| 14 | + if(nrow(x) != ncol(x)) { |
| 15 | + stop('Matrix isn\'t square. Inverse can only be calculated on square matrix') |
| 16 | + } |
| 17 | + |
| 18 | + #On creation initalize value of inverse var |
| 19 | + i <- NULL |
| 20 | + ## Save matrix data in object |
| 21 | + ## Clears any previously calculated inverse |
| 22 | + set <- function(y) { |
| 23 | + x <<- y |
| 24 | + i <<- NULL |
| 25 | + } |
| 26 | + ## Returns cached matrix data |
| 27 | + get <- function() x |
| 28 | + ## Cache inverse of matrix |
| 29 | + setInverse <- function(inverse) i <<- inverse |
| 30 | + ## Return cache inverse of matrix |
| 31 | + getInverse <- function() i |
| 32 | + |
| 33 | + list(set = set, get = get, |
| 34 | + setInverse = setInverse, |
| 35 | + getInverse = getInverse) |
| 36 | + |
8 | 37 | }
|
9 | 38 |
|
10 |
| - |
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 39 | +## Function calculates the inverse of the special "matrix" created with the makeCacheMatrix function. |
| 40 | +## 'x' is a makeCacheMatrix object |
| 41 | +## It first checks to see if the inverse has already been calculated. |
| 42 | +## If it has gets it the inverse from the cache and skips the computation. |
| 43 | +## Otherwise, it calculates the inverse of 'x' |
| 44 | +## and sets the value of the inverse matrix in the cache using the setinverse function. |
13 | 45 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 46 | + ## Looks for inverse in cache |
| 47 | + i <- x$getInverse() |
| 48 | + if(!is.null(i)) { |
| 49 | + message("getting cached data") |
| 50 | + ## Inverse is not null so return value |
| 51 | + return(i) |
| 52 | + } |
| 53 | + ## Inverse is not availble so calculate |
| 54 | + ## Get matrix data from the makeCacheMatrix object |
| 55 | + data <- x$get() |
| 56 | + ## Calculate inverse of data |
| 57 | + i <- solve(data, ...) |
| 58 | + ## Cache inverse in object |
| 59 | + x$setInverse(i) |
| 60 | + ## Return inverse of matrix |
| 61 | + i |
15 | 62 | }
|
0 commit comments