|
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 progrom computes a matrix inverse |
| 2 | +## For this assignment, assume that the matrix supplied is always invertible |
| 3 | +## |
| 4 | +## The program consists of two functions: |
| 5 | +## |
| 6 | +## One function returns a matrix inverse either |
| 7 | +## from cache or from computation with cache miss |
| 8 | +## a computed inverse is cached by design |
| 9 | +## |
| 10 | +## The other function provides handles to the original matrix and its inverse |
| 11 | +## In this function, we can set/get the original matrix |
| 12 | +## we can also set/get the matrix inverse |
5 | 13 |
|
| 14 | +## This function creates a special "matrix" object |
| 15 | +## that can cache its inverse. |
6 | 16 | makeCacheMatrix <- function(x = matrix()) {
|
| 17 | + ## initialize the invertible matrix to null |
| 18 | + b <- NULL |
7 | 19 |
|
8 |
| -} |
| 20 | + ## populate the original matrix per argument |
| 21 | + ## and initialize its inverse to null |
| 22 | + set <- function(y){ |
| 23 | + x <<- y |
| 24 | + b <<- NULL |
| 25 | + } |
| 26 | + |
| 27 | + ## fetch the original matrix |
| 28 | + get <- function() { |
| 29 | + x |
| 30 | + } |
9 | 31 |
|
| 32 | + ## populate the invertible matrix per argument |
| 33 | + setinverse <- function(inverse) { |
| 34 | + b <<- inverse |
| 35 | + } |
10 | 36 |
|
11 |
| -## Write a short comment describing this function |
| 37 | + ## fetch the invertible matrix |
| 38 | + getinverse <- function() { |
| 39 | + b |
| 40 | + } |
| 41 | + |
| 42 | + list(set = set, |
| 43 | + get = get, |
| 44 | + setinverse = setinverse, |
| 45 | + getinverse = getinverse) |
| 46 | +} |
12 | 47 |
|
| 48 | + |
| 49 | +## This function computes the inverse of the special |
| 50 | +## "matrix" returned by `makeCacheMatrix` above. If the inverse has |
| 51 | +## already been calculated (and the matrix has not changed), then |
| 52 | +## `cacheSolve` should retrieve the inverse from the cache. |
13 | 53 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 54 | + # fetch matrix inverse from cache |
| 55 | + b <- x$getinverse() |
| 56 | + |
| 57 | + # if in cache, return cached inverse |
| 58 | + if (!is.null(b)){ |
| 59 | + message("getting cached data") |
| 60 | + return(b) |
| 61 | + } |
| 62 | + |
| 63 | + # otherwise, compute the matrix inverse |
| 64 | + data <- x$get() |
| 65 | + b <- solve(data) |
| 66 | + # cache the computed inverse matrix |
| 67 | + x$setinverse(b) |
| 68 | + |
| 69 | + ## return the computed inverse matrix |
| 70 | + b |
15 | 71 | }
|
0 commit comments