|
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 | +## Perform inversion of a matrix, cache the result, and assert the cache did |
| 2 | +## work by expecting a message in console ("getting cached data") |
| 3 | +## |
| 4 | +## Then verify the inversion was computed properly by multiplying the inverted |
| 5 | +## matrix by the original matrix. Expecting an identity matrix |
5 | 6 |
|
| 7 | +## ------------------------------------------------------------ |
| 8 | +## Build a list of functions to perform the cached matrix |
6 | 9 | makeCacheMatrix <- function(x = matrix()) { |
| 10 | + # init cached result to null |
| 11 | + m <- NULL |
| 12 | + |
| 13 | + # functions |
| 14 | + setMatrix <- function(y) { |
| 15 | + x <<- y |
| 16 | + m <<- NULL |
| 17 | + } |
| 18 | + getMatrix <- function() x |
| 19 | + setMatrixInverted <- function(matrixInverted) m <<- matrixInverted |
| 20 | + getMatrixInverted <- function() m |
| 21 | + |
| 22 | + # list of functions |
| 23 | + list(setMatrix = setMatrix, |
| 24 | + getMatrix = getMatrix, |
| 25 | + setMatrixInverted = setMatrixInverted, |
| 26 | + getMatrixInverted = getMatrixInverted) |
| 27 | +} |
| 28 | + |
| 29 | +## ------------------------------------------------------------ |
| 30 | +## Search the cache or resolve and store if the result is not in cache |
| 31 | +cacheSolve <- function(x, ...) { |
| 32 | + m <- x$getMatrixInverted() |
| 33 | + if(!is.null(m)) { |
| 34 | + message("getting data From Cache") |
| 35 | + return(m) |
| 36 | + } |
| 37 | + message("Data not found in the cache . computing ...") |
| 38 | + |
| 39 | + data <- x$getMatrix() |
| 40 | + m <- inverse(data, ...) |
| 41 | + x$setMatrixInverted(m) |
| 42 | + m |
| 43 | +} |
7 | 44 |
|
| 45 | +## ------------------------------------------------------------ |
| 46 | +## Doing the actual matrix inversion |
| 47 | +inverse <- function(x){ |
| 48 | + solve(x) # ginv or solve |
8 | 49 | } |
9 | 50 |
|
| 51 | +## Apply calculation |
| 52 | +v <- cbind(c(0.5, 0.3), c(0.4, 0.9)) |
| 53 | +cv <- makeCacheMatrix(v) |
| 54 | +im <- cacheSolve(cv) |
| 55 | + |
| 56 | +## Verify results |
| 57 | +im <- cacheSolve(cv) |
| 58 | +print(im %*% v) |
10 | 59 |
|
11 | | -## Write a short comment describing this function |
12 | 60 |
|
13 | | -cacheSolve <- function(x, ...) { |
14 | | - ## Return a matrix that is the inverse of 'x' |
15 | | -} |
|
0 commit comments