|
1 |
| -## The function below creates a matrix |
2 |
| - |
| 1 | +## This pair of functions builds cache solution for inverting matrices |
| 2 | +## |
| 3 | +## First function below creates a special matrix |
3 | 4 |
|
4 | 5 | makeCacheMatrix <- function(x = matrix()) {
|
5 |
| - |
| 6 | + TheOne <- NULL |
| 7 | + set <- function(y) { |
| 8 | + x <<- y |
| 9 | + TheOne <<- NULL |
| 10 | + } |
| 11 | + get <- function() x |
| 12 | + setinverse <- function(solve) TheOne <<- solve |
| 13 | + getinverse <- function() TheOne |
| 14 | + list(set = set, get = get, |
| 15 | + setinverse = setinverse, |
| 16 | + getinverse = getinverse) |
6 | 17 | }
|
7 | 18 |
|
8 | 19 |
|
9 |
| -## This function inverses matrix, checking if this is already done. |
| 20 | +## Next function inverses matrix, checking if this is already done. |
10 | 21 | ## If so, it takes and returns cached result
|
11 | 22 |
|
12 | 23 | cacheSolve <- function(x, ...) {
|
13 |
| - ## Return a matrix that is the inverse of 'x' |
| 24 | + TheOne <- x$getinverse() |
| 25 | + if(!is.null(TheOne)) { |
| 26 | + message("Getting data from cache") |
| 27 | + return(TheOne) |
| 28 | + } |
| 29 | + data <- x$get() |
| 30 | + TheOne <- solve(data, ...) |
| 31 | + x$setinverse(TheOne) |
| 32 | + TheOne |
14 | 33 | }
|
| 34 | + |
| 35 | +## Extra code to check how the above pair works: |
| 36 | + |
| 37 | +## Creates simple 2x2 matrix |
| 38 | +c=rbind(c(1, -1/4), c(-1/4, 1)) |
| 39 | +## prints it |
| 40 | +c |
| 41 | +## inverts it and prints the result |
| 42 | +solve(c) |
| 43 | + |
| 44 | +## Creates special matrix with cache ability |
| 45 | +Mat<-makeCacheMatrix(c) |
| 46 | +## Inverts it |
| 47 | +cacheSolve(Mat) |
| 48 | +## Inverts it again, this time through cache |
| 49 | +cacheSolve(Mat) |
| 50 | + |
| 51 | +## Works! |
0 commit comments