Skip to content

Commit b6254b0

Browse files
JyeJye
authored andcommitted
Cacheable matrix inverse
Added makeCacheMatrix(x) and cacheSolve(x) to cache matrix inverse calculation.
1 parent 7f657dd commit b6254b0

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

.Rhistory

Whitespace-only changes.

cachematrix.R

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,29 @@
11
## Put comments here that give an overall description of what your
22
## functions do
33

4-
## Write a short comment describing this function
5-
4+
##Create a matrix whose inverse can be cached
65
makeCacheMatrix <- function(x = matrix()) {
7-
6+
inverse <- NULL
7+
set <- function(y) {
8+
x <<- y
9+
inverse <<- NULL
10+
}
11+
get <- function() x
12+
setInverse <- function(i) inverse <<- i
13+
getInverse <- function() inverse
14+
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
815
}
916

10-
11-
## Write a short comment describing this function
12-
17+
## Returns the cached inverse of matrix 'x'. If inverse of 'x' is not cached, it is calculated and cached.
1318
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
19+
## Return a matrix that is the inverse of 'x'
20+
inverse <- x$getInverse()
21+
if (!is.null(inverse)) {
22+
message("getting cached data")
23+
return(inverse)
24+
}
25+
data <- x$get()
26+
inverse <- solve(data, ...)
27+
x$setInverse(inverse)
28+
inverse
1529
}

0 commit comments

Comments
 (0)