|
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 | +## Assignment: Caching the Inverse of a Matrix |
5 | 2 |
|
| 3 | +## Creates a cacheMatrix which consists of a list of functions that |
| 4 | +## operates on a provided matrix. |
| 5 | +## |
| 6 | +## Usage example: |
| 7 | +## |
| 8 | +## Given the following matrix: |
| 9 | +## > x <- matrix (c(1,2,3,4), nrow=2, ncol=2) |
| 10 | +## When I execute this function: |
| 11 | +## > cacheMatrix <- makeCacheMatrix(x) |
| 12 | +## Then it returns a list of functions that operate on the matrix |
| 13 | +## And I could get the matrix by executing: |
| 14 | +## > cacheMatrix$get() |
| 15 | +## And I could set a new matrix by executing: |
| 16 | +## > cacheMatrix$set(matrix(c(4,3,2,1), nrow=2, ncol=2)) |
6 | 17 | makeCacheMatrix <- function(x = matrix()) { |
7 | | - |
| 18 | + inverse <- NULL |
| 19 | + get <- function() { x } |
| 20 | + set <- function(newMatrix) { |
| 21 | + x <<- newMatrix |
| 22 | + inverse <<- NULL |
| 23 | + } |
| 24 | + getInverse <- function() { inverse } |
| 25 | + setInverse <- function(newInverse) { |
| 26 | + inverse <<- newInverse |
| 27 | + } |
| 28 | + list(get = get, |
| 29 | + set = set, |
| 30 | + getInverse = getInverse, |
| 31 | + setInverse = setInverse) |
8 | 32 | } |
9 | 33 |
|
10 | | - |
11 | | -## Write a short comment describing this function |
12 | | - |
| 34 | +## Calculates and caches the inverse of a matrix. |
| 35 | +## |
| 36 | +## Usage example: |
| 37 | +## |
| 38 | +## Given the following cacheMatrix: |
| 39 | +## > cacheMatrix <- makeCacheMatrix(matrix(c(4,3,2,1), nrow=2, ncol=2)) |
| 40 | +## When I execute this function: |
| 41 | +## > cacheSolve(cacheMatrix) |
| 42 | +## Then I get the inverse matrix: |
| 43 | +## [,1] [,2] |
| 44 | +## [1,] -0.5 1 |
| 45 | +## [2,] 1.5 -2 |
| 46 | +## And I have now this inverse matrix cached on my cacheMatrix: |
| 47 | +## > cacheMatrix$getInverse() |
| 48 | +## [,1] [,2] |
| 49 | +## [1,] -0.5 1 |
| 50 | +## [2,] 1.5 -2 |
13 | 51 | cacheSolve <- function(x, ...) { |
14 | | - ## Return a matrix that is the inverse of 'x' |
| 52 | + inverse <- x$getInverse() |
| 53 | + if(!is.null(inverse)) { |
| 54 | + message("getting cached data") |
| 55 | + return(inverse) |
| 56 | + } |
| 57 | + data <- x$get() |
| 58 | + inverse <- solve(data) |
| 59 | + x$setInverse(inverse) |
| 60 | + inverse |
15 | 61 | } |
0 commit comments