|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## 'cacheSolve' calculates the inverse and caches |
| 2 | +## Returns cached inverse on next call |
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
| 4 | +## Stores the inverse and the matrix |
| 5 | +## Clears cached inverse, if matrix changes |
5 | 6 |
|
6 | 7 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 8 | + inverse <- NULL |
| 9 | + set <- function(m) { |
| 10 | + x <<- m |
| 11 | + inverse <<- NULL |
| 12 | + } |
| 13 | + get <- function() x |
| 14 | + setInverse <- function(inverse) inverse <<- inverse |
| 15 | + getInverse <- function() inverse |
| 16 | + list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) |
8 | 17 | }
|
9 | 18 |
|
10 | 19 |
|
11 |
| -## Write a short comment describing this function |
| 20 | + |
| 21 | +## If the inverse is already in cache, then returns cached |
| 22 | +## Else, calculates the inverse using solve function in R library and caches |
| 23 | +## Passes ... arguments to solve for inverse |
12 | 24 |
|
13 | 25 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 26 | + inv <- x$getInverse() ## Check for cached results using getInverse |
| 27 | + if(!is.null(inv)) { |
| 28 | + message("Returning cached inverse") |
| 29 | + return(inv) ## Return cached inverse |
| 30 | + } |
| 31 | + mtx <- x$get() ## get Matrix |
| 32 | + inv <- solve(mtx, ...) ## Calculate inverse |
| 33 | + x$setInverse(inv) ## Cache calculated results |
| 34 | + inv |
15 | 35 | }
|
0 commit comments