forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
73 lines (55 loc) · 1.71 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
61
62
63
64
65
66
67
68
69
70
71
72
73
# A pair of functions that cache the inverse of a matrix.
# This function creates a special "matrix" object that can cache its inverse.
# Example use:
# n <- 10
# x <- matrix(sample(1:n^2), nrow = n)
# y <- makeCacheMatrix(x)
makeCacheMatrix <- function(x = matrix()) {
# initialize the inverse
m <- NULL
# method to set the original
set <- function(y) {
x <<- y
m <<- NULL
}
# method to get the original
get <- function() {
x
}
# method to set the inverse
setsolve <- function(solve) {
m <<- solve
}
# method to get the inverse
getsolve <- function() {
m
}
# return a list with the methods
list(
set = set,
get = get,
setsolve = setsolve,
getsolve = getsolve
)
}
# This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. If the inverse has already been calculated (and the matrix has not changed), then the cacheSolve retrieves the inverse from the cache. It is assumed that the matrix supplied is always invertible.
# Example use:
# s <- cacheSolve(y) # first time run
# s <- cacheSolve(y) # getting cached data
cacheSolve <- function(x, ...) {
# use the method to get the inverse from the special "matrix" object
m <- x$getsolve()
# if the inverse is already set, return the cached inverse
if(!is.null(m)) {
message("getting cached data")
return(m)
}
# if not, get the original
data <- x$get()
# compute the inverse
m <- solve(data, ...)
# cache the inverse to the special "matrix" object
x$setsolve(m)
# and return the inverse
m
}