Skip to content

Commit 060a367

Browse files
committed
Add matrix inversion caching
1 parent 7f657dd commit 060a367

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

cachematrix.R

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,36 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Matrix inversion is usually a costly computation and there may be
2+
## some benefit to caching the inverse of a matrix rather than compute
3+
## it repeatedly. These functions help cache the inverse of a matrix.
34

4-
## Write a short comment describing this function
5+
## Creates a special "matrix" object that can cache its inverse.
56

67
makeCacheMatrix <- function(x = matrix()) {
7-
8+
m <- NULL
9+
set <- function(y) {
10+
x <<- y
11+
m <<- NULL
12+
}
13+
get <- function() x
14+
setinversematrix <- function(matrix) m <<- matrix
15+
getinversematrix <- function() m
16+
list(set = set, get = get,
17+
setinversematrix = setinversematrix,
18+
getinversematrix = getinversematrix)
819
}
920

1021

11-
## Write a short comment describing this function
22+
## Computes the inverse of the special "matrix" returned by makeCacheMatrix.
23+
## Retrieve the inverse from the cache if possible.
1224

1325
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
26+
m <- x$getinversematrix()
27+
if (!is.null(m)) {
28+
message("Getting inverse matrix from cache")
29+
return(m)
30+
}
31+
32+
data <- x$get()
33+
m <- solve(data, ...)
34+
a$setinversematrix(m);
35+
m
1536
}

0 commit comments

Comments
 (0)