-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
58 lines (53 loc) · 1.47 KB
/
cachematrix.R
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
#' Functions
#' - to create a special type of matrix and
#' - cache the result of matrix inverse calculation
#'
#' How to use:
#'
#' x <- makeCacheMatrix(matrix(c(1, 4, 2, 5), nrow=2))
#' cacheSolve(x) # calculates the inverse here
#' cacheSolve(x) # this will return the cached result
#'
#' Or
#'
#' m_example <- matrix(c(1, 4, 2, 5), nrow=2)
#' cm <- makeCacheMatrix()
#' cm$set(m_example)
#' cacheSolve(cm)
#' cacheSolve(cm)
#' returns a list with four defined methods: set, get, set_inverse, get_inverse
#'
#' @param x matrix
#' @return list with 4 methods: set, get, set_inverse, get_inverse
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
set_inverse <- function(inverse) m <<- inverse
get_inverse <- function() m
list(set = set,
get = get,
set_inverse = set_inverse,
get_inverse = get_inverse)
}
#' Inverses a matrix.
#' If the cache is available, return it.
#' If not, calculate the inverse, cache the result, and return it.
#'
#' @param x object made from makeCacheMatrix()
#' @return inverse of the given matrix.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$get_inverse()
if(!is.null(m)) {
message("getting cached inverse matrix")
return(m)
}
data <- x$get()
m <- solve(data, ...) # solve() will calculate matrix inverse in R
x$set_inverse(m)
m
}