Skip to content

Commit cdca837

Browse files
committed
Implement the cached inverse matrix
1 parent 7f657dd commit cdca837

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+
## Together, these functions create a special "matrix" object that can cache its inverse.
32

4-
## Write a short comment describing this function
3+
## The function makeCacheMatrix implements the storage of special "matrix" object.
4+
## It returns a list of closures that capture the variables x and i,
5+
## where x is the matrix being stored, and i is the cached inverse.
6+
## The four closures returned perform the following operations:
7+
## 1. set the matrix. This clears the cached inverse
8+
## 2. get the matrix
9+
## 3. set the cached inverse
10+
## 4. get the cached inverse
511

612
makeCacheMatrix <- function(x = matrix()) {
7-
13+
i <- NULL
14+
set <- function(y) {
15+
x <<- y
16+
i <<- NULL
17+
}
18+
get <- function() x
19+
setinv <- function(inv) i <<- inv
20+
getinv <- function() i
21+
list(set = set, get = get,
22+
setinv = setinv,
23+
getinv = getinv)
824
}
925

10-
11-
## Write a short comment describing this function
26+
## The function cacheSolve returns the inverse of a matrix.
27+
## It either returns it from the cache if it's
28+
## been called previously, or calculates a new one
29+
## and caches it.
1230

1331
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
32+
i <- x$getinv()
33+
if(!is.null(i)) {
34+
message("getting cached data")
35+
return(i)
36+
}
37+
data <- x$get()
38+
i <- solve(data, ...)
39+
x$setinv(i)
40+
i
1541
}

0 commit comments

Comments
 (0)