|
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 | +## This file has two functions that compute the inverse of a given |
| 2 | +## square matrix. These two assume that the provided input is a |
| 3 | +## invertible matrix |
| 4 | +## |
| 5 | +## Sample code using these functions to get matrix inverse: |
| 6 | +## > R = makeCacheMatrix(matrix(c(0,1,5,2,1,6,3,4,1),3,3)) |
| 7 | +## > cacheSolve(R) |
| 8 | +## |
5 | 9 |
|
| 10 | +## makeCacheMatrix: This function creates a special "matrix" object |
| 11 | +## that can cache its inverse. |
6 | 12 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 13 | + inverse <- NULL |
| 14 | + set <- function(y) { |
| 15 | + x <<- y |
| 16 | + inverse <<- NULL |
| 17 | + } |
| 18 | + get <- function() x |
| 19 | + setInverse <- function(solve) inverse <<- solve |
| 20 | + getInverse <- function() inverse |
| 21 | + list(set = set, get = get, |
| 22 | + setInverse = setInverse, |
| 23 | + getInverse = getInverse) |
8 | 24 | }
|
9 | 25 |
|
10 | 26 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 27 | +## cacheSolve: This function computes the inverse of the |
| 28 | +## special "matrix" returned by makeCacheMatrix function. |
| 29 | +## If the inverse has already been calculated |
| 30 | +## (and the matrix has not changed), |
| 31 | +## then the cachesolve will retrieve the inverse from the cache. |
13 | 32 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 33 | + inverse = x$getInverse() |
| 34 | + |
| 35 | + ## Return cached inverse if it already has been computed & cached |
| 36 | + if(!is.null(inverse)){ |
| 37 | + message("getting cached data") |
| 38 | + return(inverse) |
| 39 | + } |
| 40 | + |
| 41 | + data <- x$get() |
| 42 | + inverse <- solve(data,...) |
| 43 | + x$setInverse(inverse) |
| 44 | + inverse |
15 | 45 | }
|
0 commit comments