Skip to content

Commit 64be65b

Browse files
committed
Cached matrix implementation
1 parent 7f657dd commit 64be65b

File tree

1 file changed

+33
-7
lines changed

1 file changed

+33
-7
lines changed

cachematrix.R

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,41 @@
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
33

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
57

68
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)
823
}
924

1025

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
1228

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
1541
}

0 commit comments

Comments
 (0)