Skip to content

Commit 6df9f18

Browse files
committed
implement and document project
1 parent 7f657dd commit 6df9f18

File tree

1 file changed

+40
-9
lines changed

1 file changed

+40
-9
lines changed

cachematrix.R

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,46 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
51

2+
#' Meant to be used with cacheSolve. Creates a special matrix that can set/get the value of the matrix and of its inverse.
3+
#' @param x A matrix
4+
#' @return The cacheMatrix object
5+
#' @examples
6+
#' hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
7+
#' matrix11 <- hilbert(11)
8+
#' cacheMatrix11 <- makeCacheMatrix(matrix11)
9+
#' cacheSolve(cacheMatrix11)
10+
#' cacheSolve(cacheMatrix11)
11+
#' @export
612
makeCacheMatrix <- function(x = matrix()) {
7-
13+
s <- NULL
14+
set <- function(y) {
15+
x <<- y
16+
s <<- NULL
17+
}
18+
get <- function() x
19+
setSolve <- function(solve) s <<- solve
20+
getSolve <- function() s
21+
list(set = set, get = get,
22+
setSolve = setSolve,
23+
getSolve = getSolve)
824
}
925

10-
11-
## Write a short comment describing this function
12-
26+
#' Return the cached inverse if available. Otherwise, calculate and cache the inverse then return it.
27+
#' @param x The cacheMatrix
28+
#' @return the inverse. The cached inverse will be returned on subsequent calls.
29+
#' @examples
30+
#' hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
31+
#' matrix11 <- hilbert(11)
32+
#' cacheMatrix11 <- makeCacheMatrix(matrix11)
33+
#' cacheSolve(cacheMatrix11)
34+
#' cacheSolve(cacheMatrix11)
35+
#' @export
1336
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
37+
s <- x$getSolve()
38+
if(!is.null(s)) {
39+
message("getting cached data")
40+
return(s)
41+
}
42+
data <- x$get()
43+
s <- solve(data, ...)
44+
x$setSolve(s)
45+
s
1546
}

0 commit comments

Comments
 (0)