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 (45 loc) · 1.32 KB
/
Copy pathcachematrix.R
File metadata and controls
52 lines (45 loc) · 1.32 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
# Creates object/entity which stores input value (matrix) and to-be cached inversed representation
makeCacheMatrix <- function(x = matrix()) {
i <- NULL
set <- function(y) {
x <<- y
i <<- NULL
}
get <- function() x
setinverse <- function(inverse) i <<- inverse
getinverse <- function() i
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## Write a short comment describing this function
# Creates object/entity which returns cached inversed representation if already calculated or calculates it eagerly and caches it for futher usage
cacheSolve <- function(x) {
i <- x$getinverse()
if(!is.null(i)) {
message("getting cached data")
return(i)
}
data <- x$get()
i <- solve(data)
x$setinverse(i)
i
}
# Example
# A <- matrix( c(5, 1, 0,
# 3,-1, 2,
# 4, 0,-1), nrow=3, byrow=TRUE)
#
# cm <- makeCacheMatrix(A)
#
# cacheSolve(cm)
# [,1] [,2] [,3]
# [1,] 0.0625 0.0625 0.125
# [2,] 0.6875 -0.3125 -0.625
# [3,] 0.2500 0.2500 -0.500
# cacheSolve(cm)
# getting cached data
# [,1] [,2] [,3]
# [1,] 0.0625 0.0625 0.125
# [2,] 0.6875 -0.3125 -0.625
# [3,] 0.2500 0.2500 -0.500