|
1 | | -## Put comments here that give an overall description of what your |
2 | | -## functions do |
3 | | - |
4 | | -## Write a short comment describing this function |
5 | 1 |
|
| 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 |
6 | 12 | 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) |
8 | 24 | } |
9 | 25 |
|
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 |
13 | 36 | 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 |
15 | 46 | } |
0 commit comments