|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## Functions representing caching implementation of |
| 2 | +## calculating inverse of a matrix |
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
| 4 | +## Returns an object (list), which is also cacheable |
| 5 | +## matrix with getter/setter for both data and cache |
| 6 | +## values |
5 | 7 |
|
6 | 8 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 9 | + # checking the input |
| 10 | + if (!is.matrix(x)) stop("This argument doesn't look like a matrix") |
| 11 | + i <- NULL |
| 12 | + set <- function(y) { |
| 13 | + x <<- y |
| 14 | + i <<- NULL |
| 15 | + } |
| 16 | + get <- function() x |
| 17 | + # setter and getter for an inverse |
| 18 | + setinv <- function(inv) i <<- inv |
| 19 | + getinv <- function() i |
| 20 | + list(set = set, get = get, |
| 21 | + setinv = setinv, |
| 22 | + getinv = getinv) |
8 | 23 | }
|
9 | 24 |
|
10 | 25 |
|
11 |
| -## Write a short comment describing this function |
| 26 | +## Calculates inverse of a matrix returned by makeCacheMatrix |
| 27 | +## or returns cached value if it's present |
12 | 28 |
|
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 29 | +cacheSolve <- function(inversible, ...) { |
| 30 | + inv <- inversible$getinv() |
| 31 | + # checking if inverce value is already in cache |
| 32 | + if(!is.null(inv)) { |
| 33 | + message("Getting cached inverse value") |
| 34 | + return(inv) |
| 35 | + } |
| 36 | + # calculating inverse if cache is empty |
| 37 | + data <- inversible$get() |
| 38 | + inv <- solve(a=data, ...) |
| 39 | + inversible$setinv(inv) |
| 40 | + inv |
15 | 41 | }
|
0 commit comments