|
1 | | -## Put comments here that give an overall description of what your |
2 | | -## functions do |
| 1 | +## cachematrix.R |
| 2 | +## |
| 3 | +## Computing the inverse of a matrix can be a time consuming |
| 4 | +## process. If the matrix does not change, its inverse does |
| 5 | +## not change, so it is a reasonable strategy to store the |
| 6 | +## inverse when it is first needed, and retrieve the stored |
| 7 | +## value if it is needed again, which avoids the need to |
| 8 | +## recompute it. |
3 | 9 |
|
4 | | -## Write a short comment describing this function |
| 10 | +## makeCacheMatrix: |
| 11 | +## Create a list of functions which can be used to store and |
| 12 | +## manipulate a square invertible matrix and its inverse. |
| 13 | +## |
| 14 | +## If the matrix is altered (with the "set" function), any |
| 15 | +## previously cached value is likely to be invalid, so the |
| 16 | +## cache is reset. |
| 17 | +## |
| 18 | +## Returns this list of functions: |
| 19 | +## set: set the value of the matrix |
| 20 | +## get: get the value of the matrix |
| 21 | +## setinverse: set the cached value of the inverse |
| 22 | +## getinverse: get the cached value of the inverse |
5 | 23 |
|
6 | 24 | makeCacheMatrix <- function(x = matrix()) { |
7 | | - |
| 25 | + inverse <- NULL |
| 26 | + set <- function(y) { |
| 27 | + x <<- y |
| 28 | + inverse <<- NULL |
| 29 | + } |
| 30 | + get <- function() x |
| 31 | + setinverse <- function(inv) inverse <<- inv |
| 32 | + getinverse <- function() inverse |
| 33 | + list (set = set, |
| 34 | + get = get, |
| 35 | + setinverse = setinverse, |
| 36 | + getinverse = getinverse) |
8 | 37 | } |
9 | 38 |
|
10 | 39 |
|
11 | | -## Write a short comment describing this function |
| 40 | +## cacheSolve: |
| 41 | +## Return a matrix which is the inverse of the matrix created by |
| 42 | +## the "makeCacheMatrix" function. |
| 43 | +## |
| 44 | +## The first time this function is run for a matrix, it |
| 45 | +## computes the inverse and stores it, and on subsequent runs it |
| 46 | +## will return this stored value, avoiding the need to compute it |
| 47 | +## more than once. |
12 | 48 |
|
13 | 49 | cacheSolve <- function(x, ...) { |
14 | 50 | ## Return a matrix that is the inverse of 'x' |
| 51 | + inv <- x$getinverse() |
| 52 | + if(!is.null(inv)) { |
| 53 | + message("getting cached data") |
| 54 | + return(inv) |
| 55 | + } |
| 56 | + data <- x$get() |
| 57 | + inv <- solve(data) |
| 58 | + x$setinverse(inv) |
| 59 | + inv |
15 | 60 | } |
0 commit comments