Skip to content

Commit ec4c7c8

Browse files
committed
Cache inverse of a matrix
1 parent 7f657dd commit ec4c7c8

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

cachematrix.R

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,34 @@
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+
## This file provides a set of functions for caching the inverse of a matrix, for performance reasons.
52

3+
## Creates an object that represents a cached matrix. It exposes the following functions:
4+
## - set: set the value of the matrix
5+
## - get: get the value of the matrix
6+
## - setinverse: set the inverse of the matrix
7+
## - getinverse: get the inverse of the matrix
68
makeCacheMatrix <- function(x = matrix()) {
7-
9+
inverse <- NULL
10+
set <- function(y) {
11+
x <<- y
12+
inverse <<- NULL
13+
}
14+
get <- function() x
15+
setinverse <- function(inv) inverse <<- inv
16+
getinverse <- function() inverse
17+
list(set = set, get = get,
18+
setinverse = setinverse,
19+
getinverse = getinverse)
820
}
921

1022

11-
## Write a short comment describing this function
12-
23+
## Returns the inverse of a matrix, preferabily through its cached value.
1324
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
25+
inverse <- x$getinverse()
26+
if(!is.null(inverse)) {
27+
message("getting cached data")
28+
return(inverse)
29+
}
30+
data <- x$get()
31+
inverse <- solve(data, ...)
32+
x$setinverse(inverse)
33+
inverse
1534
}

0 commit comments

Comments
 (0)