Skip to content

Commit 8e59112

Browse files
author
Massimo Biancalani
committed
Created the two functions requested
1 parent 7f657dd commit 8e59112

File tree

1 file changed

+49
-8
lines changed

1 file changed

+49
-8
lines changed

cachematrix.R

Lines changed: 49 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,56 @@
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.
35

4-
## Write a short comment describing this function
56

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)
619
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)
831
}
932

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)
1343
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
1556
}

0 commit comments

Comments
 (0)