-
Notifications
You must be signed in to change notification settings - Fork 144k
/
Copy pathcachematrix.R
60 lines (48 loc) · 1.8 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
50
51
52
53
54
55
56
57
58
59
60
# Creates a special "cache-enabled matrix" object that:
# 1. Stores a matrix
# 2. Caches its inverse once calculated
# 3. Provides methods to access/update both
makeCacheMatrix <- function(x = matrix()) {
# Initialize cache for inverse (starts empty)
inv <- NULL
# Setter: Update the matrix and reset cache
set <- function(y) {
x <<- y # Store new matrix in parent environment
inv <<- NULL # Clear cached inverse when matrix changes
}
# Getter: Return the stored matrix
get <- function() x
# Cache setter: Store calculated inverse
setInverse <- function(inverse) inv <<- inverse
# Cache getter: Return cached inverse (NULL if not calculated)
getInverse <- function() inv
# Return list of accessible functions
list(set = set,
get = get,
setInverse = setInverse,
getInverse = getInverse)
}
# Computes/saves/retrieves the inverse of a cache-enabled matrix
cacheSolve <- function(x, ...) {
# Check for cached inverse
inv <- x$getInverse()
# Return cached value if available
if(!is.null(inv)) {
message("Using cached inverse")
return(inv)
}
# No cache found - calculate fresh inverse
data <- x$get() # Get original matrix
inv <- solve(data, ...) # Compute inverse (with ... args)
x$setInverse(inv) # Save result to cache
inv # Return new calculation
}
# Create cache-enabled matrix
special_matrix <- makeCacheMatrix(matrix(c(4, 3, 3, 2), 2, 2))
# First call - computes and caches
cacheSolve(special_matrix) # Returns inverse with calculation
# Subsequent calls - uses cache
cacheSolve(special_matrix) # Returns inverse with "Using cached" message
# Update matrix (auto-clears cache)
special_matrix$set(matrix(c(2, 0, 0, 2), 2, 2))
cacheSolve(special_matrix) # Recomputes fresh inverse