forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
56 lines (52 loc) · 1.78 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
#' @title Store in the cache matrix and the inverse.
#' @description
## The following functions cache the matrix inverse given a
## previous matrix. They allow avoid useless calculations.
#' makeCacheMatrix
#' \code{makeCacheMatrix} returns a special a list containing a function to retieve cached values
#'
#' @param x matrix to cache
#' @return list of methods
#' set the value of the matrix
#' get the value of the matrix
#' setInverse the value of the inverse of the matrix
#' getInverse the value of the inverse of the matrix
#' @examples
#' my_matrix <- matrix(c(1,2,2,1), nrow=2, ncol=2)
#' my_matrix_cached <- makeCacheMatrix(my_matrix)
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setInverse <- function(inverse) m <<- inverse
getInverse <- function() m
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
#' cacheSolve
#' \code{cacheSolve} returns Return a matrix that is the inverse of 'x'.
#'
#' @param the \code{makeCacheMatrix} to find inverse
#' @param ... expressions evaluated in the context of \code{solve}
#' @return the inverse matrix of 'x'
#' @examples
#' my_matrix <- matrix(c(1,2,2,1), nrow=2, ncol=2)
#' my_matrix_cached <- makeCacheMatrix(my_matrix)
#' cacheSolve(my_matrix_cached)
cacheSolve <- function(x, ...) {
m <- x$getInverse()
# if the matrix is cached return the inverse
# otherwise compute the inverse and store it in the cache
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- solve(data, ...)
x$setInverse(m)
m
}