Skip to content

Commit a8285bd

Browse files
committed
Implement makeCacheMatrix and cacheSolve functions.
1 parent 7f657dd commit a8285bd

File tree

1 file changed

+21
-9
lines changed

1 file changed

+21
-9
lines changed

cachematrix.R

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,27 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
5-
1+
## This function creates a special "matrix" object that can cache
2+
## its inverse.
63
makeCacheMatrix <- function(x = matrix()) {
7-
4+
inverse <- NULL
5+
get <- function() x
6+
get_inverse <- function() inverse
7+
set_inverse <- function(inv) {
8+
inverse <<- inv
9+
}
10+
list(get=get, get_inverse=get_inverse, set_inverse=set_inverse)
811
}
912

1013

11-
## Write a short comment describing this function
12-
14+
## This function computes the inverse of the special "matrix" returned
15+
## by makeCacheMatrix above.
16+
##
17+
## If the inverse has already been calculated (and the matrix has not
18+
## changed), then the cachesolve should retrieve the inverse from the
19+
## cache.
1320
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
21+
inv <- x$get_inverse()
22+
if (is.null(inv)) {
23+
inv <- solve(x$get(), ...)
24+
x$set_inverse(inv)
25+
}
26+
inv
1527
}

0 commit comments

Comments
 (0)