Skip to content

Commit 2f88133

Browse files
Caching the Inverse of a Matrix
1 parent 7f657dd commit 2f88133

File tree

1 file changed

+30
-8
lines changed

1 file changed

+30
-8
lines changed

cachematrix.R

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,37 @@
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+
## This is a couple of functions which is used to cache
2+
## inverse of a matrix
53

4+
## Creates a special object to store inverse of a matrix
65
makeCacheMatrix <- function(x = matrix()) {
7-
6+
inv <- NULL
7+
8+
## get & set original matrix (unused in this task)
9+
set <- function(m) {
10+
x <<- m
11+
inv <<- NULL
12+
}
13+
get <- function() x
14+
15+
## get & set the inverse of a matrix
16+
setinv <- function(inverse) inv <<- inverse
17+
getinv <- function() inv
18+
19+
list(set = set, get = get, setinv = setinv, getinv = getinv)
820
}
921

1022

11-
## Write a short comment describing this function
12-
23+
## Returns the inverse of matrix 'x'.
24+
## If the inverse is not present in cache, will calculate it and store to cache.
1325
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
26+
inv <- x$getinv()
27+
28+
if(!is.null(inv)) {
29+
message("getting cached data")
30+
return (inv)
31+
}
32+
data <- x$get()
33+
inv = solve(data, ...)
34+
x$setinv(inv)
35+
36+
inv
1537
}

0 commit comments

Comments
 (0)