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 (44 loc) · 1.28 KB
/
cachematrix.R
File metadata and controls
46 lines (44 loc) · 1.28 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
#' Meant to be used with cacheSolve. Creates a special matrix that can set/get the value of the matrix and of its inverse.
#' @param x A matrix
#' @return The cacheMatrix object
#' @examples
#' hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
#' matrix11 <- hilbert(11)
#' cacheMatrix11 <- makeCacheMatrix(matrix11)
#' cacheSolve(cacheMatrix11)
#' cacheSolve(cacheMatrix11)
#' @export
makeCacheMatrix <- function(x = matrix()) {
s <- NULL
set <- function(y) {
x <<- y
s <<- NULL
}
get <- function() x
setSolve <- function(solve) s <<- solve
getSolve <- function() s
list(set = set, get = get,
setSolve = setSolve,
getSolve = getSolve)
}
#' Return the cached inverse if available. Otherwise, calculate and cache the inverse then return it.
#' @param x The cacheMatrix
#' @return the inverse. The cached inverse will be returned on subsequent calls.
#' @examples
#' hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
#' matrix11 <- hilbert(11)
#' cacheMatrix11 <- makeCacheMatrix(matrix11)
#' cacheSolve(cacheMatrix11)
#' cacheSolve(cacheMatrix11)
#' @export
cacheSolve <- function(x, ...) {
s <- x$getSolve()
if(!is.null(s)) {
message("getting cached data")
return(s)
}
data <- x$get()
s <- solve(data, ...)
x$setSolve(s)
s
}