Skip to content

Commit 941bace

Browse files
committed
Implement cachematrix.R
1 parent 7f657dd commit 941bace

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

cachematrix.R

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,44 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## These functions implement an object in R representing a matrix with the
2+
## ability to cache its own inverse when using the cacheSolve function.
33

4-
## Write a short comment describing this function
4+
## makeCacheMatrix makes an R object to cache the inverse for a given matrix
55

66
makeCacheMatrix <- function(x = matrix()) {
7+
# initially we do not know the inverse
8+
i <- NULL
79

10+
# define the functions this object implements
11+
set <- function(y) {
12+
x <<- y
13+
# must reset cached inverse when x changes
14+
i <<- NULL
15+
}
16+
get <- function() x
17+
setinverse <- function(inverse) i <<- inverse
18+
getinverse <- function() i
19+
20+
# return the object as a list
21+
list(set = set, get = get,
22+
setinverse = setinverse,
23+
getinverse = getinverse)
824
}
925

1026

11-
## Write a short comment describing this function
27+
## cacheSolve solves the inverse for the matrix object, unless it is cached
1228

1329
cacheSolve <- function(x, ...) {
30+
# if it is cached, then just return it
31+
i <- x$getinverse()
32+
if(!is.null(i)) {
33+
# for debugging: message("getting cached data")
34+
return(i)
35+
}
36+
37+
# otherwise, solve and cache it for future use
38+
data <- x$get()
39+
i <- solve(data, ...)
40+
x$setinverse(i)
41+
1442
## Return a matrix that is the inverse of 'x'
43+
i
1544
}

0 commit comments

Comments
 (0)