|
1 | | -## Put comments here that give an overall description of what your |
2 | | -## functions do |
| 1 | +#' @title Store in the cache matrix and the inverse. |
| 2 | +#' @description |
| 3 | +## The following functions cache the matrix inverse given a |
| 4 | +## previous matrix. They allow avoid useless calculations. |
3 | 5 |
|
4 | | -## Write a short comment describing this function |
5 | 6 |
|
| 7 | +#' makeCacheMatrix |
| 8 | +#' \code{makeCacheMatrix} returns a special a list containing a function to retieve cached values |
| 9 | +#' |
| 10 | +#' @param x matrix to cache |
| 11 | +#' @return list of methods |
| 12 | +#' set the value of the matrix |
| 13 | +#' get the value of the matrix |
| 14 | +#' setInverse the value of the inverse of the matrix |
| 15 | +#' getInverse the value of the inverse of the matrix |
| 16 | +#' @examples |
| 17 | +#' my_matrix <- matrix(c(1,2,2,1), nrow=2, ncol=2) |
| 18 | +#' my_matrix_cached <- makeCacheMatrix(my_matrix) |
6 | 19 | makeCacheMatrix <- function(x = matrix()) { |
7 | | - |
| 20 | + m <- NULL |
| 21 | + set <- function(y) { |
| 22 | + x <<- y |
| 23 | + m <<- NULL |
| 24 | + } |
| 25 | + get <- function() x |
| 26 | + setInverse <- function(inverse) m <<- inverse |
| 27 | + getInverse <- function() m |
| 28 | + list(set = set, get = get, |
| 29 | + setInverse = setInverse, |
| 30 | + getInverse = getInverse) |
8 | 31 | } |
9 | 32 |
|
10 | | - |
11 | | -## Write a short comment describing this function |
12 | | - |
| 33 | +#' cacheSolve |
| 34 | +#' \code{cacheSolve} returns Return a matrix that is the inverse of 'x'. |
| 35 | +#' |
| 36 | +#' @param the \code{makeCacheMatrix} to find inverse |
| 37 | +#' @param ... expressions evaluated in the context of \code{solve} |
| 38 | +#' @return the inverse matrix of 'x' |
| 39 | +#' @examples |
| 40 | +#' my_matrix <- matrix(c(1,2,2,1), nrow=2, ncol=2) |
| 41 | +#' my_matrix_cached <- makeCacheMatrix(my_matrix) |
| 42 | +#' cacheSolve(my_matrix_cached) |
13 | 43 | cacheSolve <- function(x, ...) { |
14 | | - ## Return a matrix that is the inverse of 'x' |
| 44 | + |
| 45 | + m <- x$getInverse() |
| 46 | + # if the matrix is cached return the inverse |
| 47 | + # otherwise compute the inverse and store it in the cache |
| 48 | + if(!is.null(m)) { |
| 49 | + message("getting cached data") |
| 50 | + return(m) |
| 51 | + } |
| 52 | + data <- x$get() |
| 53 | + m <- solve(data, ...) |
| 54 | + x$setInverse(m) |
| 55 | + m |
15 | 56 | } |
0 commit comments