|
3 | 3 |
|
4 | 4 | ## Write a short comment describing this function
|
5 | 5 |
|
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
7 |
| - |
| 6 | +makeCacheMatrix <- function( m = matrix() ) { |
| 7 | + |
| 8 | + ## Initialize the inverse property |
| 9 | + i <- NULL |
| 10 | + |
| 11 | + ## Method to set the matrix |
| 12 | + set <- function( matrix ) { |
| 13 | + m <<- matrix |
| 14 | + i <<- NULL |
| 15 | + } |
| 16 | + |
| 17 | + ## Method the get the matrix |
| 18 | + get <- function() { |
| 19 | + ## Return the matrix |
| 20 | + m |
| 21 | + } |
| 22 | + |
| 23 | + ## Method to set the inverse of the matrix |
| 24 | + setInverse <- function(inverse) { |
| 25 | + i <<- inverse |
| 26 | + } |
| 27 | + |
| 28 | + ## Method to get the inverse of the matrix |
| 29 | + getInverse <- function() { |
| 30 | + ## Return the inverse property |
| 31 | + i |
| 32 | + } |
| 33 | + |
| 34 | + ## Return a list of the methods |
| 35 | + list(set = set, get = get, |
| 36 | + setInverse = setInverse, |
| 37 | + getInverse = getInverse) |
8 | 38 | }
|
9 | 39 |
|
10 | 40 |
|
| 41 | + |
11 | 42 | ## Write a short comment describing this function
|
12 | 43 |
|
13 | 44 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 45 | + |
| 46 | + ## Return a matrix that is the inverse of 'x' |
| 47 | + m <- x$getInverse() |
| 48 | + |
| 49 | + ## Just return the inverse if its already set |
| 50 | + if( !is.null(m) ) { |
| 51 | + message("getting cached data") |
| 52 | + return(m) |
| 53 | + } |
| 54 | + |
| 55 | + ## Get the matrix from our object |
| 56 | + data <- x$get() |
| 57 | + |
| 58 | + ## Calculate the inverse using matrix multiplication |
| 59 | + m <- solve(data) %*% data |
| 60 | + |
| 61 | + ## Set the inverse to the object |
| 62 | + x$setInverse(m) |
| 63 | + |
| 64 | + ## Return the matrix |
| 65 | + m |
15 | 66 | }
|
0 commit comments