|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## JHDS Certification - R Programming |
| 2 | +## |
| 3 | +## Rodrigo Duran :: https://github.com/rduran/ProgrammingAssignment2 |
| 4 | +## |
| 5 | +## Assignment: Caching the Inverse of a Matrix |
| 6 | +## |
| 7 | +## Computing the inverse of a square matrix can be done with the solve function |
| 8 | +## in R. For example, if X is a square invertible matrix, then solve(X) returns |
| 9 | +## its inverse. |
| 10 | +## |
| 11 | +## For this assignment, assume that the matrix supplied is always invertible. |
3 | 12 |
|
4 |
| -## Write a short comment describing this function |
5 | 13 |
|
| 14 | +## |
| 15 | +## makeCacheMatrix: This function creates a special "matrix" object that can cache |
| 16 | +## its inverse |
| 17 | +## |
6 | 18 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 19 | + cached <<- NULL |
| 20 | + |
| 21 | + ## makes sure that cached element is empty |
| 22 | + set <- function(y) { |
| 23 | + x <<- y |
| 24 | + cached <<- NULL |
| 25 | + } |
| 26 | + |
| 27 | + ## Retreives the original matrix |
| 28 | + get <- function() x |
| 29 | + |
| 30 | + ## Caches the inverse |
| 31 | + setInverse <- function(x) cached <<- x |
| 32 | + |
| 33 | + ## Retreives the cached value |
| 34 | + getInverse <- function() cached |
| 35 | + |
| 36 | + ## Expose the API for caching |
| 37 | + list( set = set, get = get, setInverse = setInverse, |
| 38 | + getInverse = getInverse) |
8 | 39 | }
|
9 | 40 |
|
10 |
| - |
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 41 | +## |
| 42 | +## cacheSolve: This function computes the inverse of the special "matrix" |
| 43 | +## returned by makeCacheMatrix above. If the inverse has already |
| 44 | +## been calculated (and the matrix has not changed), then the |
| 45 | +## cachesolve should retrieve the inverse from the cache. |
| 46 | +## |
13 | 47 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 48 | + ## Retrieves the cached inverse matrix |
| 49 | + inv_m <- x$getInverse() |
| 50 | + if( !is.null(inv_m) ) { |
| 51 | + message("getting cached data") |
| 52 | + return(inv_m) |
| 53 | + } |
| 54 | + |
| 55 | + ## If the cached inverse matrix is null, proceed with calculation |
| 56 | + m <- x$get() # Retrieves the orignal matrix |
| 57 | + inv_m <- solve(m, ...) # Calculates the inverse matrix |
| 58 | + x$setInverse(inv_m) # Caches the inverse matrix |
| 59 | + |
| 60 | + inv_m |
15 | 61 | }
|
0 commit comments