|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +### Assignment: Caching the Inverse of a Matrix |
3 | 2 |
|
4 |
| -## Write a short comment describing this function |
| 3 | +## Description: Matrix inversion is usually a costly computation |
| 4 | +## and there may be some benefit to caching the inverse of a |
| 5 | +## matrix rather than computing it repeatedly. This pair of |
| 6 | +## functions cache the inverse of a matrix. |
5 | 7 |
|
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
7 | 8 |
|
| 9 | +## This function creates a special "matrix" object |
| 10 | +## that can cache its inverse. |
| 11 | + |
| 12 | +makeCacheMatrix <- function(x = matrix()) { |
| 13 | + m <- NULL |
| 14 | + set <- function(y) { |
| 15 | + x <<- y |
| 16 | + m <<- NULL |
| 17 | + } |
| 18 | + get <- function() x |
| 19 | + setinverse <- function(solve) m <<- solve |
| 20 | + getinverse <- function() m |
| 21 | + list(set = set, get = get, |
| 22 | + setinverse = setinverse, |
| 23 | + getinverse = getinverse) |
| 24 | + |
8 | 25 | }
|
9 | 26 |
|
10 | 27 |
|
11 |
| -## Write a short comment describing this function |
| 28 | +## This function computes the inverse of the special "matrix" returned |
| 29 | +## by `makeCacheMatrix` above. If the inverse has already been |
| 30 | +## calculated (and the matrix has not changed), then |
| 31 | +## `cacheSolve` should retrieve the inverse from the cache. |
12 | 32 |
|
13 | 33 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 34 | + ## Return a matrix that is the inverse of 'x' |
| 35 | + m <- x$getinverse() |
| 36 | + if(!is.null(m)) { |
| 37 | + message("getting cached data") |
| 38 | + return(m) |
| 39 | + } |
| 40 | + data <- x$get() |
| 41 | + m <- solve(data, ...) |
| 42 | + x$setinverse(m) |
| 43 | + m |
15 | 44 | }
|
0 commit comments