|
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 | +## Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of |
| 2 | +## a matrix rather than compute it repeatedly. |
| 3 | +## makeCacheMatrix and cacheSolve can be used to create a matrix that is able to cache its inverse. |
| 4 | +## Typical usage: |
| 5 | +## ```` |
| 6 | +## m <- makeCacheMatrix(matrix(1:4,2,2)) |
| 7 | +## cacheSolve(m) |
| 8 | +## m$get() |
| 9 | +## cacheSolve(m) |
| 10 | +## ```` |
5 | 11 |
|
| 12 | +## makeCacheMatrix creates a special "matrix", which is really a list containing a function to |
| 13 | +## 1. set the value of the matrix |
| 14 | +## 2. get the value of the matrix |
| 15 | +## 3. set the value of the inverse matrix |
| 16 | +## 4. get the value of the inverse metrix |
6 | 17 | makeCacheMatrix <- function(x = matrix()) {
|
| 18 | + |
| 19 | + i <- NULL |
| 20 | + set <- function(y) { |
| 21 | + x <<- y |
| 22 | + i <<- NULL |
| 23 | + } |
| 24 | + get <- function() x |
| 25 | + setinverse <- function(inverse) i <<- inverse |
| 26 | + getinverse <- function() i |
| 27 | + list(set = set, get = get, |
| 28 | + setinverse = setinverse, |
| 29 | + getinverse = getinverse) |
7 | 30 |
|
8 | 31 | }
|
9 | 32 |
|
10 | 33 |
|
11 |
| -## Write a short comment describing this function |
| 34 | +## cacheSolve takes a cached matrix as argument and returns the inverse of the matrix. |
| 35 | +## The inverse is stored inside the cached matrix on first call, then retrived from the cache on subsequent calls. |
12 | 36 |
|
13 | 37 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 38 | + ## Return a matrix that is the inverse of 'x' |
| 39 | + i <- x$getinverse() |
| 40 | + if(!is.null(i)) { |
| 41 | + message("getting cached data") |
| 42 | + return(i) |
| 43 | + } |
| 44 | + data <- x$get() |
| 45 | + i <- solve(data, ...) |
| 46 | + x$setinverse(i) |
| 47 | + i |
15 | 48 | }
|
0 commit comments