-
Notifications
You must be signed in to change notification settings - Fork 143k
Expand file tree
/
Copy path.Rhistory
More file actions
32 lines (32 loc) · 846 Bytes
/
Copy path.Rhistory
File metadata and controls
32 lines (32 loc) · 846 Bytes
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
# Function to create a special matrix object that can cache its inverse
makeCacheMatrix <- function(mat = matrix()) {
inv <- NULL
set <- function(matrix) {
mat <<- matrix
inv <<- NULL
}
get <- function() mat
setInverse <- function(inverse) {
inv <<- inverse
}
getInverse <- function() inv
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
}
# Function to compute the inverse of the matrix and cache the result
cacheSolve <- function(cacheMatrix) {
inv <- cacheMatrix$getInverse()
if (!is.null(inv)) {
message("Getting cached inverse")
return(inv)
}
mat <- cacheMatrix$get()
inv <- solve(mat)
cacheMatrix$setInverse(inv)
inv
}
# Create a sample matrix
A <- matrix(c(1, 2, 3, 4), nrow = 2)
# Create a cache-enabled matrix object
cachedMatrix <- makeCacheMatrix(A)
# Compute and cache the inverse
cacheSolve(cachedMatrix)