|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 |
| - |
4 |
| -## Write a short comment describing this function |
5 |
| - |
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 1 | +## Note: names of the methods changed to follow guidlines suggested here: |
| 2 | +## https://google-styleguide.googlecode.com/svn/trunk/Rguide.xml#identifiers |
7 | 3 |
|
| 4 | +## factory function to create a matrix that can cache the value of its inverse |
| 5 | +MakeCacheMatrix <- function(x = matrix()) { |
| 6 | + # initialize the cached value of matrix inverse to be NULL |
| 7 | + inverse.cache <- NULL |
| 8 | + |
| 9 | + # create setter function to... |
| 10 | + Set <- function(y) { |
| 11 | + # ...store the matrix |
| 12 | + x <<- y |
| 13 | + # ...and reset the cached inverse value |
| 14 | + inverse.cache <<- NULL |
| 15 | + } |
| 16 | + |
| 17 | + # create getter function - return incapsulated matrix |
| 18 | + Get <- function() x |
| 19 | + |
| 20 | + SetInverse <- function(inverse) inverse.cache <<- inverse |
| 21 | + |
| 22 | + GetInverse <- function() inverse.cache |
| 23 | + |
| 24 | + list(Set = Set, Get = Get, |
| 25 | + SetInverse = SetInverse, |
| 26 | + GetInverse = GetInverse) |
8 | 27 | }
|
9 | 28 |
|
10 | 29 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 30 | +## Calculate the inverse of the matrix; get the cached inverse matrix if it exists |
| 31 | +CacheSolve <- function(x, ...) { |
| 32 | + # get cached inverse |
| 33 | + inverse <- x$GetInverse() |
| 34 | + # ...return cached inverse if it exists |
| 35 | + if(!is.null(inverse)) { |
| 36 | + message("getting cached data") |
| 37 | + return(inverse) |
| 38 | + } |
| 39 | + # otherwise get the matrix |
| 40 | + data <- x$Get() |
| 41 | + # ...calculate inverse |
| 42 | + inverse <- solve(data, ...) |
| 43 | + # ...and cache it |
| 44 | + x$SetInverse(inverse) |
| 45 | + # return calculated inverse matrix object |
| 46 | + inverse |
15 | 47 | }
|
0 commit comments