-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
49 lines (33 loc) · 1.04 KB
/
cachematrix.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
# Method to set the matrix
set <- function(y) {
x <<- y
inv <<- NULL # Reset the inverse property whenever the matrix is changed
}
# Method to get the matrix
get <- function() x
# Method to set the inverse of the matrix
setInverse <- function(inverse) inv <<- inverse
# Method to get the inverse of the matrix
getInverse <- function() inv
# Return the list of methods
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
}
## Write a short comment describing this function
cacheSolve <- function(x, ...) {
inv <- x$getInverse() # Try to get the cached inverse
# If the inverse is already cached, return it
if (!is.null(inv)) {
message("getting cached data")
return(inv)
}
# Otherwise, compute the inverse
mat <- x$get()
inv <- solve(mat, ...) # Use solve to compute the inverse
# Cache the inverse
x$setInverse(inv)
# Return the inverse
inv
}