|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 |
| - |
4 |
| -## Write a short comment describing this function |
| 1 | +## makeCacheMatrix creates a special matrix that can keep the |
| 2 | +## original matrix and inverse of the matrix (if set) |
| 3 | +## cacheSolve receives an instance of makeCacheMatrix and |
| 4 | +## checks if inverse is available in cache. If not, computes the inverse, |
| 5 | +## saves to the cache, and return the result |
5 | 6 |
|
| 7 | +## This function wraps a matrix and returns a list of |
| 8 | +## operation to set and get the matrix and it's inverse matrix |
6 | 9 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 10 | + inverseMatrix <- NULL |
| 11 | + set <- function(inputMatrix) { |
| 12 | + x <<- inputMatrix |
| 13 | + inverseMatrix <<- NULL |
| 14 | + } |
| 15 | + get <- function() x |
| 16 | + setInverse <- function(inverseM) inverseMatrix <<- inverseM |
| 17 | + getInverse <- function() { |
| 18 | + inverseMatrix |
| 19 | + } |
| 20 | + list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) |
8 | 21 | }
|
9 | 22 |
|
10 | 23 |
|
11 |
| -## Write a short comment describing this function |
| 24 | + |
| 25 | +## This function returns the inverse of matrix stored in parameter |
| 26 | +## It first checks for cache, if not availalbe, computes the cache. |
| 27 | +## Otherwise just returns from the cache. |
12 | 28 |
|
13 | 29 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 30 | + |
| 31 | + inverseMatrix <- x$getInverse() |
| 32 | + |
| 33 | + if(!is.null(inverseMatrix)) { ## Found in cache |
| 34 | + return(inverseMatrix) |
| 35 | + } |
| 36 | + |
| 37 | + m <- x$get() |
| 38 | + inverseMatrix <- solve(m) |
| 39 | + x$setInverse(inverseMatrix) |
| 40 | + inverseMatrix |
15 | 41 | }
|
0 commit comments