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
46 lines (40 loc) · 1.05 KB
/
cachematrix.R
File metadata and controls
46 lines (40 loc) · 1.05 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
## Two functions to calculate inverse of matrix and store cached result
## Defines 4 subfunctions for getting and storing data
makeCacheMatrix <- function(x = matrix()) {
matrCached <- NULL
set <- function(y) {
x <<- y
matr <<- NULL
}
get <- function() x
setmatrix <- function(y) matrCached <<- y
getmatrix <- function() matrCached
list(set = set, get = get,
setmatrix = setmatrix,
getmatrix = getmatrix)
}
## This function checks if there is already calculated matrix and returns it
## If not, then calculate it and store.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$getmatrix()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- solve(data, ...)
x$setmatrix(m)
m
}
## test it:
# > test <- makeCacheMatrix(matrix(c(4,3,3,2),2,2))
# > cacheSolve(test)
# [,1] [,2]
# [1,] -2 3
# [2,] 3 -4
# > cacheSolve(test)
# getting cached data
# [,1] [,2]
# [1,] -2 3
# [2,] 3 -4