Skip to content

Commit 8b7139c

Browse files
committed
Added functionality for caching matrix inverse
1 parent 7f657dd commit 8b7139c

File tree

1 file changed

+32
-7
lines changed

1 file changed

+32
-7
lines changed

cachematrix.R

Lines changed: 32 additions & 7 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+
## Matrix inversion is usually a costly computation, this module creates an API
2+
## to cache the inverse of a matrix rather than compute it repeatedly
53

4+
## makeCacheMatrix: This function creates a special "matrix" object that
5+
## can cache its inverse.
66
makeCacheMatrix <- function(x = matrix()) {
7+
inv <- NULL
78

8-
}
9+
set <- function(y) {
10+
x <<- y
11+
inv <<- NULL
12+
}
13+
get <- function() x
914

15+
setsolve <- function(solve) inv <<- solve
16+
getsolve <- function() inv
17+
18+
list(set = set,
19+
get = get,
20+
setsolve = setsolve,
21+
getsolve = getsolve)
22+
}
1023

11-
## Write a short comment describing this function
1224

25+
## cacheSolve: This function computes the inverse of the special "matrix"
26+
## returned by makeCacheMatrix above. If the inverse has
27+
## already been calculated (and the matrix has not changed),
28+
## then the cachesolve should retrieve the inverse from the cache.
1329
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
30+
## Return a matrix that is the inverse of 'x'
31+
inv <- x$getsolve()
32+
if(!is.null(inv)) {
33+
message("getting cached data")
34+
return(inv)
35+
}
36+
data <- x$get()
37+
inv <- solve(data)
38+
x$setsolve(inv)
39+
inv
1540
}

0 commit comments

Comments
 (0)