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

Skip to content

Commit ae5eefe

Browse files
committed
cache matrix inversion
1 parent 7f657dd commit ae5eefe

File tree

1 file changed

+46
-7
lines changed

1 file changed

+46
-7
lines changed

cachematrix.R

Lines changed: 46 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,54 @@
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+
## Special wrapper of a matrix in cases where we need cheaper repeat access to the inverse.
52

3+
## Build the matrix wrapper
64
makeCacheMatrix <- function(x = matrix()) {
5+
## by default we do not have an inverse.
6+
inv <- NULL
77

8+
## Allow the caller to set a new matrix in place of the use used at initialisation.
9+
set <- function( y ) {
10+
x <<- y
11+
## make sure an eventual cached inverse is cleared
12+
inv <<- NULL
13+
}
14+
15+
## Return the matrix
16+
get <- function() {
17+
x
18+
}
19+
20+
## cache the inverse
21+
setinverse <- function( inverse ) {
22+
inv <<- inverse
23+
}
24+
25+
## return the inverse
26+
getinverse <- function() {
27+
inv
28+
}
829
}
930

1031

11-
## Write a short comment describing this function
12-
32+
## Given an object returned by makeCacheMatrix, calculate the inverse and cache it for further calls.
33+
## If a cached inverse has already been calculated on the wrapped matrix, the cached version is returned.
1334
cacheSolve <- function(x, ...) {
1435
## Return a matrix that is the inverse of 'x'
15-
}
36+
37+
inv <- x$getinverse
38+
39+
if( ! is.null( inv ) ) {
40+
## The wrapped matrix has a non NULL inverse
41+
message( "cache hit" )
42+
return inv
43+
}
44+
45+
## Calculate the inverse using solve
46+
## TODO: handle special cases more carefully, not all matrices can be inverted.
47+
inv <- solve( x$get() )
48+
49+
## Cache the result of solve()
50+
x$setinverse( inv )
51+
52+
## return the inverse
53+
inv
54+
}

0 commit comments

Comments
 (0)