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

Skip to content

Commit 592ff33

Browse files
committed
Added matrix caching functionality
1 parent 7f657dd commit 592ff33

File tree

1 file changed

+45
-9
lines changed

1 file changed

+45
-9
lines changed

cachematrix.R

Lines changed: 45 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,51 @@
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+
## Solving for the inverse of a given (non-singular) matrix
2+
## Subsequent calls will use a cached value for the inverse, if available
53

4+
## Initialize a matrix environment with caching, define interface functions
65
makeCacheMatrix <- function(x = matrix()) {
7-
6+
# the inverse starts out undefined
7+
inverse <- NULL
8+
9+
# save a new matrix
10+
set <- function(y) {
11+
x <<- y
12+
# the inverse of a new matrix will begin undefined
13+
inverse <<- NULL
14+
}
15+
16+
# return the currently loaded matrix
17+
get <- function() x
18+
19+
# save the inverse of the current matrix
20+
setinv <- function(inv) inverse <<- inv
21+
22+
# return the inverse
23+
getinv <- function() inverse
24+
25+
# when initialized, return the four subfunctions of this environment
26+
list(set = set, get = get, setinv = setinv, getinv = getinv)
827
}
928

10-
11-
## Write a short comment describing this function
12-
29+
## Takes a predefined matrix (from makeCacheMatrix) and returns its inverse
30+
## Will use a cached value if available, if not it will be solved for and saved
1331
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
32+
# ask the matrix environment for a cached inverse
33+
inverse <- x$getinv()
34+
35+
# check if the inverse is cached already, if so just return it
36+
if(!is.null(inverse)) {
37+
message("matrix inverse found in cache! let's use it")
38+
return(inverse)
39+
}
40+
41+
# no cached value found, solve for the inverse
42+
message("matrix inverse NOT found in cache! we'll have to solve for it")
43+
matrix <- x$get()
44+
inverse <- solve(matrix, ...)
45+
46+
# save the newly solved for inverse to the matrix environment
47+
x$setinv(inverse)
48+
49+
# return the inverse as requested
50+
inverse
1551
}

0 commit comments

Comments
 (0)