Skip to content

Commit 6687fe3

Browse files
committed
The cacheMatrix functions:
1) cacheSolve which takes in a makeCacheMatrix()-created object 2) makeCacheMatrix which creates the cached matrix
1 parent 7f657dd commit 6687fe3

File tree

1 file changed

+31
-9
lines changed

1 file changed

+31
-9
lines changed

cachematrix.R

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,37 @@
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+
## These two functions work together to cache matrix inverse operations on its input as key
52

3+
## This function creates a special "matrix", which is really a list containing functions:
4+
## set: sets the value of the matrix
5+
## get: gets the value of the matrix
6+
## setinverse: sets the value of the inverse
7+
## getinverse: gets the value of the inverse
68
makeCacheMatrix <- function(x = matrix()) {
7-
9+
m <- NULL
10+
set <- function(y) {
11+
x <<- y
12+
m <<- NULL
13+
}
14+
get <- function() x
15+
setinverse <- function(inverse) m <<- inverse
16+
getinverse <- function() m
17+
list(set = set, get = get,
18+
setinverse = setinverse,
19+
getinverse = getinverse)
820
}
921

10-
11-
## Write a short comment describing this function
12-
22+
## This function calculates the inverse of the special "matrix" created with the above function.
23+
## However, it first checks to see if the inverse has already been calculated.
24+
## If so, it gets the inverse from the cache and skips the computation.
25+
## Otherwise, it calculates the inverse of the data and sets the value of the inverse in the cache via the setinverse function.
1326
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
27+
## Return a matrix that is the inverse of 'x'
28+
m <- x$getinverse()
29+
if(!is.null(m)) {
30+
message("getting cached data")
31+
return(m)
32+
}
33+
data <- x$get()
34+
m <- solve(data, ...)
35+
x$setinversesolve(m)
36+
m
1537
}

0 commit comments

Comments
 (0)