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
52 lines (48 loc) · 1.26 KB
/
Copy pathcachematrix.R
File metadata and controls
52 lines (48 loc) · 1.26 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
## matrix functions to cache a matrix inverse
## solve for inverse matrix only once and
## cache inverse to return on subsequent requests
makeCacheMatrix <- function(x = matrix()) {
## crate a matrix object
## eg use >myMatrix = makeCacheMatrix(matrix(data=c(1:4),nrow=2,ncol=2))
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setinverse <- function(solve) inv <<- solve
getinverse <- function() inv
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
## x must be a square invertible matrix created with makeCacheMatrix
## eg. use >cachSolve(myMatrix)
inv <- x$getinv()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
data <- x$get()
inv <- solve(data, ...)
x$setinv(inv)
inv
}
# example usage
# > v4 <- makeCacheMatrix()
# > v4$set(matrix(c(99,13,5,26),nrow=2,ncol=2))
# > v4$get()
# [,1] [,2]
# [1,] 99 5
# [2,] 13 26
# > cacheSolve(v4)
# [,1] [,2]
# [1,] 0.010362694 -0.001992826
# [2,] -0.005181347 0.039457951
# > cacheSolve(v4)
# getting cached data
# [,1] [,2]
# [1,] 0.010362694 -0.001992826
# [2,] -0.005181347 0.039457951