Skip to content

Commit 6ad21a4

Browse files
committed
committing my work
1 parent 7f657dd commit 6ad21a4

File tree

1 file changed

+32
-9
lines changed

1 file changed

+32
-9
lines changed

cachematrix.R

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,38 @@
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+
## This file contains code to create an object that is able to cache a matrix's inverse
52

3+
## This function creates a special matrix object that has attributes to get and set both the matrix and its inverse
64
makeCacheMatrix <- function(x = matrix()) {
7-
5+
inverse <- NULL
6+
set <- function(y) {
7+
x <<- y
8+
inverse <<- NULL
9+
}
10+
get <- function() x
11+
setInverse <- function(inverse) inverse <<- inverse
12+
getInverse <- function() inverse
13+
list(set = set, get = get,
14+
setInverse = setInverse,
15+
getInverse = getInverse)
816
}
917

10-
11-
## Write a short comment describing this function
12-
18+
## This function returns the specified matrix's inverse from cache, if available, and computes and stores the inverse in cache if the cache is not available.
1319
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
20+
inverse <- x$getInverse()
21+
# if inverse is not null (it was in the cache), return it
22+
if(!is.null(inverse)) {
23+
message("getting inverse from cache")
24+
return(inverse)
25+
}
26+
# otherwise, get the matrix's data, compute the inverse, and store it in cache
27+
data <- x$get()
28+
inverse <- solve(data, ...)
29+
x$setInverse(inverse)
30+
inverse # return the newly computed and stores inversesolv
1531
}
32+
33+
34+
## "Tests"
35+
# m <- matrix(c(0, 2, 1, 0), nrow = 2, ncol = 2, byrow = TRUE)
36+
# cm <- makeCacheMatrix(m)
37+
# cacheSolve(cm) # works!
38+
# cacheSolve(cm) == solve(m) # tells me cm$getInverse() has the same value as solve(m)

0 commit comments

Comments
 (0)