Skip to content

Commit 5ddc12e

Browse files
committed
Cached matrix implementation
1 parent 7f657dd commit 5ddc12e

File tree

1 file changed

+33
-8
lines changed

1 file changed

+33
-8
lines changed

cachematrix.R

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,40 @@
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+
## Pair of function for calculating the inverse of matrix.
2+
## Apart of calculating the inverse; it caches the result, so
3+
## that when next time inverse is called for the same matrix
4+
## cached data will be used.
55

6+
## Creates special matrix which can cache the inverse
7+
## of this matrix
68
makeCacheMatrix <- function(x = matrix()) {
7-
9+
i <- NULL
10+
set <- function(y) {
11+
x <<- y
12+
i <<- NULL
13+
}
14+
get <- function() x
15+
setinv <- function(inv) i <<- inv
16+
getinv <- function() i
17+
list(set = set, get = get,
18+
setinv = setinv,
19+
getinv = getinv)
820
}
921

1022

11-
## Write a short comment describing this function
12-
23+
## Returns the cached inverse of the matrix if it is already
24+
## caculated. If it is not cached then inverse is computed, cached and returned.
1325
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
26+
i <- x$getinv()
27+
if(!is.null(i)) {
28+
message("getting cached inverse of matrix")
29+
return(i)
30+
}
31+
data <- x$get()
32+
i <- solve(data)
33+
x$setinv(i)
34+
i
1535
}
36+
37+
## usage:
38+
## > source('cachematrix.R')
39+
## > cm <- makeCacheMatrix(actualMatrix)
40+
## > inv <- cacheSolve(cm)

0 commit comments

Comments
 (0)