|
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 | +## This project will compute the inverse of a matrix and save it in a cache. |
| 2 | +## If a cached version exists, it will retrieve the cached version rather than |
| 3 | +## performing the computation a second time. |
| 4 | +## |
| 5 | +## |
| 6 | +## makeCacheMatrix: This function creates a special "matrix" object that can |
| 7 | +## cache its inverse. |
5 | 8 |
|
6 | 9 | makeCacheMatrix <- function(x = matrix()) { |
7 | | - |
| 10 | + ## using variable m because it was used in makeVector example |
| 11 | + m <- NULL |
| 12 | + |
| 13 | + ## 1. set the value of the matrix |
| 14 | + set <- function(y) { |
| 15 | + x <<- y |
| 16 | + m <<- NULL |
| 17 | + } |
| 18 | + |
| 19 | + ## 2. set the value of the matrix |
| 20 | + get <- function() x |
| 21 | + |
| 22 | + ## 3. set the value of the inverse |
| 23 | + setinverse <- function(inverse) m <<- inverse |
| 24 | + |
| 25 | + ## 4.get the value of the inverse |
| 26 | + getinverse <- function() m |
| 27 | + list(set = set, |
| 28 | + get = get, |
| 29 | + setinverse = setinverse, |
| 30 | + getinverse = getinverse) |
8 | 31 | } |
9 | 32 |
|
10 | 33 |
|
11 | | -## Write a short comment describing this function |
| 34 | +## cacheSolve: This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. If the inverse has already been calculated (and the matrix has not changed), then the cachesolve should retrieve the inverse from the cache. |
12 | 35 |
|
13 | 36 | cacheSolve <- function(x, ...) { |
14 | | - ## Return a matrix that is the inverse of 'x' |
| 37 | + ## Return a matrix that is the inverse of 'x' |
| 38 | + ## Again, using m because this was the variable name in the example cachemean |
| 39 | + m <- x$getinverse() |
| 40 | + if (!is.null(m)) { ## cached version already exists |
| 41 | + message("getting cached data") |
| 42 | + return(m) |
| 43 | + } |
| 44 | + data <- x$get() |
| 45 | + m <- solve(data, ...) |
| 46 | + x$setinverse(m) |
| 47 | + m |
15 | 48 | } |
0 commit comments