forked from catalinp99/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
60 lines (47 loc) · 1.51 KB
/
Copy pathcachematrix.R
File metadata and controls
60 lines (47 loc) · 1.51 KB
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
## Pair of functions that cache the inverse of a matrix
## Usage: Pass the result of a makeCacheMatrix call to cacheSolve
#' Util function that set the matrix and the inverse in an environment
#' @param x an invertible matrix
#' examples
#' x = makeCacheMatrix(matrix(rnorm(9), 3, 3))
#' x$set(matrix(rnorm(16), 4, 4))
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL # This will store the cached inverse matrix
# Function to set the matrix
set <- function(y) {
x <<- y
inv <<- NULL # Invalidate the cached inverse because the matrix has changed
}
# Function to get the matrix
get <- function() {
x
}
# Function to set the inverse matrix
setInverse <- function(inverse) {
inv <<- inverse
}
# Function to get the inverse matrix
getInverse <- function() {
inv
}
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
}
#' Compute and cache the inverse of a matrix
#' @param x the result of a previous makeCacheMatrix call
#' @param ... additional arguments to pass to solve function
#' examples
#' x = makeCacheMatrix(matrix(rnorm(9), 3, 3))
#' cacheSolve(x)
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)
}
# If the inverse is not cached, compute it
mat <- x$get()
inv <- solve(mat, ...) # Compute the inverse
x$setInverse(inv) # Cache the inverse
inv # Return the inverse
}