|
1 | | -## Put comments here that give an overall description of what your |
2 | | -## functions do |
3 | 1 |
|
4 | | -## Write a short comment describing this function |
5 | 2 |
|
6 | | -makeCacheMatrix <- function(x = matrix()) { |
| 3 | +## It creates the special "matrix" and provides accesses |
| 4 | +## to retreive and set both the original matrix and its inverse. |
| 5 | + |
7 | 6 |
|
| 7 | +makeCacheMatrix <- function(x = matrix()) { |
| 8 | + inverse <- NULL |
| 9 | + set <- function(y) { # set a new matrix |
| 10 | + x <<- y |
| 11 | + inverse <<- NULL # When the matrix is set, the (cached) inverse is set to NULL |
| 12 | + } |
| 13 | + get <- function() x # get matrix |
| 14 | + setInverse <- function(inv) inverse <<- inv ##Inverse function |
| 15 | + getInverse <- function() inverse |
| 16 | + list(set = set, |
| 17 | + get = get, |
| 18 | + setInverse = setInverse, |
| 19 | + getInverse = getInverse) |
8 | 20 | } |
9 | 21 |
|
| 22 | +## It calculates the inverse of the matrix provided by makeCacheMatrix |
10 | 23 |
|
11 | | -## Write a short comment describing this function |
12 | 24 |
|
13 | 25 | cacheSolve <- function(x, ...) { |
14 | | - ## Return a matrix that is the inverse of 'x' |
| 26 | + ## Return a matrix that is the inverse of 'x' |
| 27 | + inv <- x$setInverse() # get the cached inverse |
| 28 | + if(!is.null(inv)) { # checks if the CacheMatrix has a cached inverse |
| 29 | + message("getting cached inverse") |
| 30 | + return(inv) # return the cached inverse and exit the function |
| 31 | + } |
| 32 | + mat <- x$get() # retrive the original matrix |
| 33 | + mat.inv <- solve(mat, ...) # invert the original matrix |
| 34 | + x$setInverse(mat.inv) # put the inverse matrix calculated in the cache |
| 35 | + mat.inv # return the inverse of the input matrix |
15 | 36 | } |
0 commit comments