|
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 their may be some |
| 2 | +## benefit to caching the inverse of a matrix rather than compute it repeatedly. |
| 3 | +## Folowing pair of functions that cache the inverse of a matrix. |
5 | 4 |
|
| 5 | +## The first function, makeCacheMatrix creates a special "matrix", which is |
| 6 | +## really a list containing a function to |
| 7 | +## 1. set the value of the matrix |
| 8 | +## 2. get the value of the matrix |
| 9 | +## 3. set the value of the inversed matrix |
| 10 | +## 4. get the value of the inversed matrix |
6 | 11 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 12 | + s <- NULL |
| 13 | + set <- function(y) { |
| 14 | + x <<- y |
| 15 | + s <<- NULL |
| 16 | + } |
| 17 | + get <- function() x |
| 18 | + setsolve <- function(solve) s <<- solve |
| 19 | + getsolve <- function() s |
| 20 | + list(set = set, get = get, |
| 21 | + setsolve = setsolve, |
| 22 | + getsolve = getsolve) |
8 | 23 | }
|
9 | 24 |
|
10 |
| - |
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 25 | +## The following function calculates the inversed matrix of the special "matix" |
| 26 | +## created with the above function. However, it first checks to see if the |
| 27 | +## inversed matrix has already been calculated. If so, it gets the inversed |
| 28 | +## matrix from the cache and skips the computation. Otherwise, it calculates the |
| 29 | +## inversed matrix of the data and sets the value of the inversion in the cache |
| 30 | +## via the setsolve function. |
13 | 31 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 32 | + s <- x$getsolve() |
| 33 | + if(!is.null(s)) { |
| 34 | + message("getting cached data") |
| 35 | + return(s) |
| 36 | + } |
| 37 | + data <- x$get() |
| 38 | + s <- solve(data, ...) |
| 39 | + x$setsolve(s) |
| 40 | + s |
15 | 41 | }
|
0 commit comments