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
51 lines (36 loc) · 1.21 KB
/
cachematrix.R
File metadata and controls
51 lines (36 loc) · 1.21 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
rm(list = ls())
library(simpleCache)
# creates a matrix, invert the matrix, load matrix from cache
makeCacheMatrix <- function(m = matrix()) {
iv <- NULL
setMatrix <- function(y) {
m <<- y
iv <<- NULL
}
getMatrix <-function() m
setinverse <- function(invM) iv <<- invM
getinverse <- function() simpleCache("inverse")
list(setMatrix = setMatrix, getMatrix = getMatrix, setinverse = setinverse,
getinverse = getinverse)
}
# The following function inverts a matrix created with the above function.
# However, it first checks to see if the mean has already been calculated.
# If so, it gets the inverted matrix from the cache and skips the computation.
# Otherwise, it creates and sets in the cache via the setinverse function.
cacheSolve <- function(x, ...) {
invM <- x$getinverse()
if(!is.null(invM)){
message("getting cached inverse matrix")
}
data <- x$getMatrix()
invM <- solve(data)
print(x$setinverse(invM))
cacheDir <- tempdir()
setCacheDir(cacheDir)
simpleCache("inverse", {x$setinverse(invM)}, recreate = TRUE)
print( listCaches())
print(invM)
}
M <- matrix(c(1:4), 2, 2)
func <- makeCacheMatrix(M)
cacheSolve(func)