|
3 | 3 |
|
4 | 4 | ## Write a short comment describing this function
|
5 | 5 |
|
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 6 | +### Jairo's comments |
| 7 | + |
| 8 | +### Matrix inversion is usually a costly computation, if there is need to compute many times |
| 9 | +### the same, store the result of inverse of a matrix in the cache and return the result |
| 10 | +### when need is more efficient than compute it repeatedly. |
| 11 | + |
| 12 | +### following two functions are used to cache the inverse of a matrix. |
| 13 | + |
| 14 | +### makeCacheMatrix creates a matrix object that can cache its inverse |
7 | 15 |
|
| 16 | +makeCacheMatrix <- function(x = matrix()) { |
| 17 | + ## Initialize the inverse property |
| 18 | + inv <- NULL |
| 19 | + |
| 20 | + ### set the value of the matrix |
| 21 | + set <- function(y) { |
| 22 | + x <<- y |
| 23 | + inv <<- NULL |
| 24 | + } |
| 25 | + |
| 26 | + ### get the value of the matrix |
| 27 | + get <- function() x |
| 28 | + |
| 29 | + ### set the value of inverse of the matrix |
| 30 | + setinverse <- function(inverse) inv <<- inverse |
| 31 | + |
| 32 | + ### get the value of inverse of the matrix |
| 33 | + getinverse <- function() inv |
| 34 | + |
| 35 | + ### Return list of the methods |
| 36 | + list(set=set, get=get, setinverse=setinverse, getinverse=getinverse) |
8 | 37 | }
|
9 | 38 |
|
10 | 39 |
|
11 | 40 | ## Write a short comment describing this function
|
12 | 41 |
|
| 42 | +### Jairo's comments |
| 43 | + |
| 44 | +### This function returns the inverse of the matrix. |
| 45 | +### 1. It first checks if the inverse has already been computed. If exist, it returns the result |
| 46 | +### and skips the computation. |
| 47 | +### 2. If not, it computes the inverse, stores the value in the cache via setinverse function. |
| 48 | + |
13 | 49 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 50 | + ## Return a matrix that is the inverse of 'x' |
| 51 | + inv <- x$getinverse() |
| 52 | + |
| 53 | + ## If the inverse already set, return it |
| 54 | + if(!is.null(inv)) { |
| 55 | + message("getting cached data.") |
| 56 | + return(inv) |
| 57 | + } |
| 58 | + |
| 59 | + ## Get the matrix from our object |
| 60 | + data <- x$get() |
| 61 | + |
| 62 | + ## Compute the inverse using matrix multiplication |
| 63 | + inv <- solve(data) |
| 64 | + |
| 65 | + ## Set the value to the object and return it |
| 66 | + x$setinverse(inv) |
| 67 | + inv |
15 | 68 | }
|
0 commit comments