This repository was archived by the owner on Feb 10, 2026. It is now read-only.
forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
56 lines (49 loc) · 1.44 KB
/
cachematrix.R
File metadata and controls
56 lines (49 loc) · 1.44 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
## These functions calculate the inverse of a matrix and cache the result.
## On subsequent calls, the cached will be used to avoid repetitive calculations
## Using the given matrix, create a list of functions to do the caching
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setinverse <- function(inverse) inv <<- inverse
getinverse <- function() inv
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## Calculate the inverted matrix, or return the cached value if calculated already
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getinverse()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
data <- x$get()
inv <- solve(data, ...)
x$setinverse(inv)
inv
}
## Sample use:
## > # Create a sample matrix
## > m <- matrix( 1:4, 2, 2)
## > m
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
## > # Make a cacheMatrix
## > cm <- makeCacheMatrix(m)
## > # Apply the function to solve it
## > cacheSolve(cm)
## [,1] [,2]
## [1,] -2 1.5
## [2,] 1 -0.5
## > # Apply again to check the use of cache
## > cacheSolve(cm)
## getting cached data
## [,1] [,2]
## [1,] -2 1.5
## [2,] 1 -0.5