|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## This assignment will show us how to store objects in the cache. The |
| 2 | +## functions will compute the inverse of a matrix but return the inverse |
| 3 | +## from the cache if it has already been calculated and set in the cache. |
3 | 4 |
|
4 |
| -## Write a short comment describing this function |
5 | 5 |
|
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 6 | +## This function creates list of functions to set and get objects from the cache. |
| 7 | +## The functions and the objects can be accessed from the parent invironment if |
| 8 | +## assigned to an object in the parent environment. |
7 | 9 |
|
| 10 | +makeCacheMatrix <- function(x = matrix()) |
| 11 | +{ |
| 12 | + inv <- NULL |
| 13 | + set <- function(y) ## Set the matrix in the cache |
| 14 | + { |
| 15 | + x <<- y |
| 16 | + inv <<- NULL |
| 17 | + } |
| 18 | + get <- function() x ## Return the cached matrix |
| 19 | + setinverse <- function(inverse) inv <<- inverse ## Set the inverse in the cache |
| 20 | + getinverse <- function() inv ##Return the chached inverse |
| 21 | + list(set = set, get = get, |
| 22 | + setinverse = setinverse, |
| 23 | + getinverse = getinverse) |
8 | 24 | }
|
9 | 25 |
|
| 26 | +## This function computes the inverse but returns the inverse from the cache |
| 27 | +## if it has already been calculated and set in the cache |
10 | 28 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 29 | +cacheSolve <- function(x, ...) |
| 30 | +{ |
| 31 | + ## Return a matrix that is the inverse of 'x' |
| 32 | + inv <- x$getinv() |
| 33 | + if(!is.null(inv)) ## Check if the inverse has been calculated |
| 34 | + { |
| 35 | + message("getting cached data") |
| 36 | + return(inv) |
| 37 | + } |
| 38 | + data <- x$get() ## Calculate inverse |
| 39 | + inverse <- solve(data, ...) |
| 40 | + x$setinv(inverse) |
| 41 | + inv |
15 | 42 | }
|
0 commit comments