Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5448ea3

Browse files
committed
implemented makeCacheMatrix and cacheSolve for caching matrix inverse
1 parent e4eed41 commit 5448ea3

File tree

1 file changed

+37
-5
lines changed

1 file changed

+37
-5
lines changed

cachematrix.R

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,47 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## The provided functions create a matrix which knows how to
2+
## cache it's inverse when needed.
3+
## Usage:
4+
## m = makeCacheMatrix(mymatrix)
5+
## cacheSolve(m) # computes and caches on the first call
6+
## cacheSolve(m) # returns cache on subsequent calls
37

4-
## Write a short comment describing this function
8+
9+
## Make a version of the matrix which is used to save the cache of the inverse
510

611
makeCacheMatrix <- function(x = matrix()) {
12+
inverse.cache <- NULL
13+
set <- function(y) {
14+
x <<- y
15+
inverse.cache <<- NULL
16+
}
17+
get <- function() x
18+
setinverse <- function(inverse) inverse.cache <<- inverse
19+
getinverse <- function() inverse.cache
720

21+
# return the list of functions that allow the cache to be manipulated
22+
list(set = set,
23+
get = get,
24+
setinverse = setinverse,
25+
getinverse = getinverse)
26+
827
}
928

1029

11-
## Write a short comment describing this function
30+
## Return the cached inverse of a matrix or
31+
## compute and cache the inverse if not cached.
1232

1333
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
34+
# see if we have the inverse cached
35+
inverse <- x$getinverse()
36+
if(!is.null(inverse)) {
37+
message("using cached inverse")
38+
} else {
39+
message("computing and caching inverse")
40+
# not cached, get the matrix and invert it
41+
data <- x$get()
42+
inverse <- solve(data, ...)
43+
# save the inverse in the cache
44+
x$setinverse(inverse)
45+
}
46+
inverse
1547
}

0 commit comments

Comments
 (0)