Skip to content

Commit dccb98e

Browse files
updated functions of caching
Commit rdpeng#1
1 parent 7f657dd commit dccb98e

File tree

1 file changed

+47
-12
lines changed

1 file changed

+47
-12
lines changed

cachematrix.R

Lines changed: 47 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,50 @@
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+
# Define the special matrix functions
62
makeCacheMatrix <- function(x = matrix()) {
7-
3+
inv <- NULL
4+
5+
# Function to set the matrix
6+
set <- function(matrix) {
7+
x <<- matrix
8+
inv <<- NULL
9+
}
10+
11+
# Function to get the matrix
12+
get <- function() {
13+
x
14+
}
15+
16+
# Function to set the inverse of the matrix
17+
setInverse <- function(inverse) {
18+
inv <<- inverse
19+
}
20+
21+
# Function to get the inverse of the matrix
22+
getInverse <- function() {
23+
inv
24+
}
25+
26+
# Return a list of functions
27+
list(set = set,
28+
get = get,
29+
setInverse = setInverse,
30+
getInverse = getInverse)
831
}
932

10-
11-
## Write a short comment describing this function
12-
13-
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
33+
cacheSolve <- function(cache, ...) {
34+
inv <- cache$getInverse()
35+
36+
# If the inverse is already calculated, return it
37+
if (!is.null(inv)) {
38+
message("Getting cached inverse")
39+
return(inv)
40+
}
41+
42+
# Otherwise, calculate the inverse
43+
data <- cache$get()
44+
inv <- solve(data, ...)
45+
46+
# Cache the inverse
47+
cache$setInverse(inv)
48+
49+
inv
50+
}

0 commit comments

Comments
 (0)