|
1 | 1 | ## Put comments here that give an overall description of what your
|
2 | 2 | ## functions do
|
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
5 |
| - |
| 4 | +## makeCacheMatrix function takes a single argument x |
| 5 | +## Return value: a list consisting of four methods |
| 6 | +## set: set the value of x, also resetting cached inverse |
| 7 | +## get: retrieve the value of x |
| 8 | +## setinverse: set the cached inverse |
| 9 | +## getinverse: get the cached inverse |
6 | 10 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 11 | + inv <- NULL |
| 12 | + set <- function(y) { |
| 13 | + x <<- y |
| 14 | + inv <<- NULL |
| 15 | + } |
| 16 | + get <- function() x |
| 17 | + setinverse <- function(inv2) inv <<- inv2 |
| 18 | + getinverse <- function() inv |
| 19 | + list(set = set, get = get, |
| 20 | + setinverse = setinverse, |
| 21 | + getinverse = getinverse) |
8 | 22 | }
|
9 | 23 |
|
10 | 24 |
|
11 |
| -## Write a short comment describing this function |
| 25 | +## cachedSolve calculates the inverse of a matrix x |
| 26 | +## using cached inverse |
12 | 27 |
|
13 | 28 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 29 | + #print(x) |
| 30 | + inverse <- x$getinverse() |
| 31 | + if(!is.null(inverse)) { |
| 32 | + # if cached inverse is found |
| 33 | + # then simply return the cached inverse |
| 34 | + message("getting cached inverse") |
| 35 | + return(inverse) |
| 36 | + } |
| 37 | + |
| 38 | + # otherwise calculates the inverse using solve |
| 39 | + # and store the value in cached inverse |
| 40 | + data <- x$get() |
| 41 | + inverse <- solve(data, ...) |
| 42 | + x$setinverse(inverse) |
| 43 | + |
| 44 | + inverse |
15 | 45 | }
|
0 commit comments