Skip to content

Commit 75b7140

Browse files
Update cachematrix.R
1 parent 7f657dd commit 75b7140

File tree

1 file changed

+35
-8
lines changed

1 file changed

+35
-8
lines changed

cachematrix.R

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,42 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
1+
## Pair of functions that cache the inverse of a matrix
2+
## Usage: Pass the result of a makeCacheMatrix call to cacheSolve
53

4+
#' Util function that set the matrix and the inverse in an environment
5+
#' @param x an invertible matrix
6+
#' examples
7+
#' x = makeCacheMatrix(matrix(rnorm(9), 3, 3))
8+
#' x$set(matrix(rnorm(16), 4, 4))
69
makeCacheMatrix <- function(x = matrix()) {
7-
10+
# todo error if x is not a matrix
11+
inv <- NULL
12+
set <- function(y) {
13+
x <<- y
14+
inv <<- NULL
15+
}
16+
get <- function() x
17+
setinverse <- function(inverse) inv <<- inverse
18+
getinverse <- function() inv
19+
list(set = set, get = get,
20+
setinverse = setinverse,
21+
getinverse = getinverse)
822
}
923

1024

11-
## Write a short comment describing this function
12-
25+
#' Compute and cache the inverse of a matrix
26+
#' @param x the result of a previous makeCacheMatrix call
27+
#' @param ... additional arguments to pass to solve function
28+
#' examples
29+
#' x = makeCacheMatrix(matrix(rnorm(9), 3, 3))
30+
#' cacheSolve(x)
1331
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
32+
## Return a matrix that is the inverse of 'x'
33+
inv <- x$getinverse()
34+
if(!is.null(inv)) {
35+
message("getting cached matrix inverse")
36+
return(inv)
37+
}
38+
data <- x$get()
39+
inv <- solve(data, ...)
40+
x$setinverse(inv)
41+
inv
1542
}

0 commit comments

Comments
 (0)