|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## The Below functions demonstrate the principle of caching via lexical closure. |
| 2 | +## This can speed up program execution by avoiding recomputing values. |
| 3 | +## The functions below are modifications of the examples given for caching the |
| 4 | +## mean of a vector. |
3 | 5 |
|
4 |
| -## Write a short comment describing this function |
5 | 6 |
|
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 7 | +## This function takes a matrix and returns a list containing: |
| 8 | +## "set" and "get" - functions to set and get the value of the matrix. |
| 9 | +## "setinverse" and "getinverse" - functions to comptute and retreive the inverse of the matrix |
7 | 10 |
|
| 11 | +makeCacheMatrix <- function(x = matrix()) { |
| 12 | + m <- NULL |
| 13 | + set <- function(y) { |
| 14 | + x <<- y |
| 15 | + m <<- NULL #defines m and sets it to NULL |
| 16 | + } |
| 17 | + get <- function() x |
| 18 | + setinverse <- function(inverse) m <<- inverse ## sets m to the value of "inverse" in the environment where m is defined |
| 19 | + getinverse <- function() m #returns m (as opposed to the uninverted x) |
| 20 | + list(set = set, get = get, |
| 21 | + setinverse = setinverse, |
| 22 | + getinverse = getinverse) |
8 | 23 | }
|
9 | 24 |
|
10 | 25 |
|
11 |
| -## Write a short comment describing this function |
| 26 | +## This as an extension of the R "solve" function to handle a list returned |
| 27 | +## by makeCacheMatrix |
12 | 28 |
|
13 | 29 | cacheSolve <- function(x, ...) {
|
14 | 30 | ## Return a matrix that is the inverse of 'x'
|
| 31 | + m <- x$getinverse() |
| 32 | + if(!is.null(m)) { #if m is defined |
| 33 | + message("getting cached data") |
| 34 | + return(m) |
| 35 | + } |
| 36 | + mat <- x$get() #otherwise |
| 37 | + m <- solve(mat, ...) #invert m |
| 38 | + x$setinverse(m) #and cache the value |
| 39 | + m #now return m |
15 | 40 | }
|
0 commit comments