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

Skip to content

Commit a0749d2

Browse files
committed
Implement a matrix with a cached inverse
1 parent 7f657dd commit a0749d2

File tree

1 file changed

+32
-5
lines changed

1 file changed

+32
-5
lines changed

cachematrix.R

Lines changed: 32 additions & 5 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
1+
## Matrix inversion is usually a costly computation,
2+
## so there may be some benefit to caching the inverse of a matrix
3+
## rather than computing it repeatedly.
4+
## The following functions implement the matrix inverse caching mechanism
35

4-
## Write a short comment describing this function
6+
## This function creates a special "matrix" object that can cache its inverse
57

68
makeCacheMatrix <- function(x = matrix()) {
9+
inverse <- NULL
710

11+
set <- function(y) {
12+
x <<- y
13+
inverse <<- NULL
14+
}
15+
get <- function() x
16+
setinverse <- function(i) inverse <<- i
17+
getinverse <- function() inverse
18+
19+
list(set = set, get = get,
20+
setinverse = setinverse,
21+
getinverse = getinverse)
822
}
923

1024

11-
## Write a short comment describing this function
25+
## This function computes the inverse of the special "matrix"
26+
## returned by makeCacheMatrix above.
27+
## If the inverse has already been calculated (and the matrix has not changed),
28+
## then cacheSolve retrieves the inverse from the cache
1229

1330
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
31+
i <- x$getinverse()
32+
33+
if(!is.null(i)) {
34+
message("getting cached data")
35+
return(i)
36+
}
37+
38+
data <- x$get()
39+
i <- solve(data, ...)
40+
x$setinverse(i)
41+
i
1542
}

0 commit comments

Comments
 (0)