|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## Solution to Programming Assigment 2 |
| 2 | +## creates 2 functions - |
| 3 | +## one for creating a special type of object that can cache the matrix inverse; |
| 4 | +## another for checking if the inverse is already in the cache and returing it if so. Otherwise it calculates the inverse and caches it |
3 | 5 |
|
4 |
| -## Write a short comment describing this function |
| 6 | +## Usage demonstration: |
| 7 | +## create a matrix that we will use for testing: |
| 8 | +## m1 <- matrix(c(4,5,6,3,4,5,11,44,66), 3,3) |
5 | 9 |
|
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 10 | +## create a special object that holds the matrix and its inverse. There is no inverse yet: |
| 11 | +## ca1 <- makeCacheMatrix(m1) |
| 12 | +## get the matrix inverse. There is no pre-cached inverse, so it has to be calculated: |
| 13 | +## u <- cacheSolve(ca1) |
| 14 | +## print the inverse: |
| 15 | +## u |
| 16 | +## [,1] [,2] [,3] |
| 17 | +## [1,] -4.00000000 13.0000000 -8.00000000 |
| 18 | +## [2,] 6.00000000 -18.0000000 11.00000000 |
| 19 | +## [3,] -0.09090909 0.1818182 -0.09090909 |
| 20 | +## |
| 21 | +## get the matrix inverse again. This time is it retrieved from cache and a message is displayed: |
| 22 | +## w <- cacheSolve(ca1) |
| 23 | +## we have cached matrix, returning |
| 24 | +## |
| 25 | +## print the inverse to verify that it is the same |
| 26 | +## w |
7 | 27 |
|
| 28 | +## Creates an object that can hold a matrix and its inverse |
| 29 | +makeCacheMatrix <- function(x = matrix()) { |
| 30 | + i <- NULL |
| 31 | + getMatrix <- function() x |
| 32 | + setMatrix <- function(y) { |
| 33 | + x <<- y |
| 34 | + i <<- NULL |
| 35 | + } |
| 36 | + getInverse <- function() i |
| 37 | + setInverse <- function(inverse) { |
| 38 | + i <<- inverse |
| 39 | + } |
| 40 | + list(getMatrix = getMatrix, setMatrix = setMatrix, getInverse = getInverse, setInverse = setInverse) |
8 | 41 | }
|
9 | 42 |
|
10 | 43 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 44 | +## Accepts special object that holds a matrix and its inverse |
| 45 | +## returns an inverse from the cache if there is one. Otherwise calculates the inverse, caches it returns it. |
13 | 46 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 47 | + i <- x$getInverse() |
| 48 | + if (!is.null(i)) { |
| 49 | + message("we have cached matrix, returning it") |
| 50 | + return(i) |
| 51 | + } |
| 52 | + ## there is no inverse calculated for this matrix yet. |
| 53 | + ## getting the matrix from the special object: |
| 54 | + matrix <- x$getMatrix() |
| 55 | + ## calculating the inverse |
| 56 | + inverse <- solve(matrix) |
| 57 | + ## caching in the special object that is held in the parent environment |
| 58 | + x$setInverse(inverse) |
| 59 | + inverse |
15 | 60 | }
|
0 commit comments