|
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 "vector", |
| 2 | +# which is really a list containing a function to |
| 3 | +# a) set the value of the matrix |
| 4 | +# b) get the value of the matrix |
| 5 | +# c) set the value of the inverse of the matrix |
| 6 | +# d) get the value of the inverse of the matrix |
5 | 7 |
|
6 | 8 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 9 | + inv <- NULL |
| 10 | + ## Update existing matrix |
| 11 | + set <- function(y){ |
| 12 | + x <<- y |
| 13 | + inv <<- NULL |
| 14 | + } |
| 15 | + ## Return original matrix |
| 16 | + get <- function() x |
| 17 | + ### Set the inverse of the matrix |
| 18 | + setinverse <- function(inverse) inv <<- inverse |
| 19 | + ### Return the inverse of the matrix |
| 20 | + getinverse <- function() inv |
| 21 | + list(set = set, get = get, |
| 22 | + setinverse = setinverse, |
| 23 | + getinverse = getinverse) |
8 | 24 | }
|
9 | 25 |
|
10 |
| - |
11 |
| -## Write a short comment describing this function |
| 26 | +## cacheSolve performs following tasks: |
| 27 | +# 1) check if inverse of the matrix is already created or not |
| 28 | +# 2) return the inverse of the matrix if cached inverse found |
| 29 | +# 3) compute inverse of the matrix if no cache found |
| 30 | +# 4) cache the inverse of the matrix |
| 31 | +# 5) return the inverse of the matrix |
12 | 32 |
|
13 | 33 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 34 | + inv <- x$getinverse() |
| 35 | + ## check if inverse of the matrix is cached |
| 36 | + if(!is.null(inv)) { |
| 37 | + ## return cache if cache is found |
| 38 | + message("getting cached data") |
| 39 | + return(inv) |
| 40 | + } |
| 41 | + ## if cache is not found, then get the inverse of the matrix. |
| 42 | + ## first, get the original matrix |
| 43 | + data <- x$get() |
| 44 | + ## then get a inverse |
| 45 | + inv <- solve(data, ...) |
| 46 | + ### cache retrieved value |
| 47 | + x$setinverse(inv) |
| 48 | + inv |
15 | 49 | }
|
0 commit comments