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
73 lines (62 loc) · 2.03 KB
/
cachematrix.R
File metadata and controls
73 lines (62 loc) · 2.03 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
61
62
63
64
65
66
67
68
69
70
71
72
73
## These functions create a cached matrix object
## that allows user to calculate matrix inverse once and cache it
## rather than recomputing each time.
## This function creates a matrix object
## with the ability to cache the inverse
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setsolve <- function(solve) m <<- solve
getsolve <- function() m
list(set = set, get = get,
setsolve = setsolve,
getsolve = getsolve)
}
## This function on the first call
## will solve the inverse of a "cached matrix" object
## return the inverse and store that inverse in the cache
## on the subsequent calls it retreives the cache rather than recomputing
## the cache retrieval is flagged by the print statement
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$getsolve()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- solve(data, ...)
x$setsolve(m)
m
}
# ------------------------------------------------------------
# example
# ------------------------------------------------------------
# x=matrix(1:9,nrow=3)
# x[3,2]=0
# x
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 2 5 8
# [3,] 3 0 9
# solve(x)
# [,1] [,2] [,3]
# [1,] -1.2500000 1.0000000 0.08333333
# [2,] -0.1666667 0.3333333 -0.16666667
# [3,] 0.4166667 -0.3333333 0.08333333
# xc <- makeCacheMatrix(x)
# cacheSolve(xc)
# [,1] [,2] [,3]
# [1,] -1.2500000 1.0000000 0.08333333
# [2,] -0.1666667 0.3333333 -0.16666667
# [3,] 0.4166667 -0.3333333 0.08333333
# cacheSolve(xc)
# getting cached data <---------------------------------
# [,1] [,2] [,3]
# [1,] -1.2500000 1.0000000 0.08333333
# [2,] -0.1666667 0.3333333 -0.16666667
# [3,] 0.4166667 -0.3333333 0.08333333