|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +# Create a CacheMatrix, a special Matrix object that can cache its inverse (available by calling getInverse) |
| 2 | +makeCacheMatrix <- function(x = matrix()) { |
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
| 4 | + # Initialize inverse as null (will be calculated on demand) |
| 5 | + inverse <- NULL |
| 6 | + |
| 7 | + # A set function to set the Matrix and reset the cached inverse |
| 8 | + set <- function(y) { |
| 9 | + x <<- y |
| 10 | + inverse <<- NULL |
| 11 | + } |
5 | 12 |
|
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 13 | + # Get function to retrieve the Matrix |
| 14 | + get <- function() x |
7 | 15 |
|
8 |
| -} |
| 16 | + # Functions to set and get the cached inverse |
| 17 | + setInverse <- function(solve) inverse <<- solve |
| 18 | + getInverse <- function() inverse |
9 | 19 |
|
| 20 | + # Return list of the wrapped functions of the matrix |
| 21 | + list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) |
| 22 | +} |
10 | 23 |
|
11 |
| -## Write a short comment describing this function |
12 | 24 |
|
| 25 | +# Check if the inverse has already been calculated for this matrix and return it if so, otherwise calculate and cache the inversex |
13 | 26 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 27 | + |
| 28 | + # check if the inverse has been cached already |
| 29 | + inverse <- x$getInverse() |
| 30 | + |
| 31 | + if(!is.null(inverse)) { |
| 32 | + message("Using Cached inverse") |
| 33 | + # Use the cached inverse |
| 34 | + return(inverse) |
| 35 | + } |
| 36 | + |
| 37 | + # Inverse not cached, calculate and cache it |
| 38 | + inverse <- solve(x$get(),...) |
| 39 | + x$setInverse(inverse) |
| 40 | + inverse |
15 | 41 | }
|
0 commit comments