forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachematrix.R
61 lines (43 loc) · 1.43 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
## Function pair to cache the inverse of a matrix rather than computing
## it repeatedly
## create a special "matrix" object to cache inverse
makeCacheMatrix <- function(x = matrix()) {
## create empty matrix for inverse
s <- NULL
set <- function(y) {
## set matrix
x <<- y
## clear inverse
s <<- NULL
}
## return matrix
get <- function() x
## set s to computed inverse
setsolve <- function(solve) s <<- solve
## return inverse
getsolve <- function() s
## Matrix object
list(set = set, get = get,
setsolve = setsolve,
getsolve = getsolve)
}
## compute the inverse of the special "matrix" returned by
## makeCacheMatrix above (represented by x)
cacheSolve <- function(x, ...) {
## Assign inverse to s
s <- x$getsolve()
## Return inverse if already calculated and abort function
if(!is.null(s)) {
message("getting cached data")
return(s)
}
## When s is empty
## get matrix
data <- x$get()
## compute inverse
s <- solve(data, ...)
## set the inverse in the matrix object
x$setsolve(s)
## return the inverse
s
}