Skip to content

Commit 24ef7a0

Browse files
committed
filled in the assignment code. created memoized method call and special 'cache' solve for matrix
1 parent 7f657dd commit 24ef7a0

File tree

1 file changed

+39
-6
lines changed

1 file changed

+39
-6
lines changed

cachematrix.R

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,48 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Taking the inverse of a matrix can be a very expensive operation
2+
## for very large matricies. These methods allow one to cache
3+
## the expensive operation so that if called again, the value
4+
## will be retuned much faster. This technique is also known
5+
## as memoization in computer science.
6+
##
7+
## Example:
8+
## > testm <- makeCacheMatrix(matrix(c(2:5),2,2))
9+
## > cacheSolve(testm) #expensive operation
10+
## > cacheSolve(testm) #cache hit on second run
311

4-
## Write a short comment describing this function
512

6-
makeCacheMatrix <- function(x = matrix()) {
13+
## This function will create a special version of matrix
14+
## which will encapsulate the matrix value as well as the
15+
## inverse of the matrix. This contains getters and setters
16+
## for these values.
717

18+
makeCacheMatrix <- function(x = matrix()) {
19+
inv <- NULL
20+
set <- function(y) {
21+
x <<- y
22+
inv <<- NULL
23+
}
24+
get <- function() x
25+
setinv <- function(i) inv <<- i
26+
getinv <- function() inv
27+
28+
list(set = set, get = get,
29+
setinv = setinv,
30+
getinv = getinv)
831
}
932

1033

11-
## Write a short comment describing this function
34+
## This will check to see if there is a cached inverse value.
35+
## If not found, the inverse will be calculated, caached and
36+
## returned.
1237

1338
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
39+
inv <- x$getinv()
40+
if (!is.null(inv)) {
41+
message("cache hit")
42+
return(inv)
43+
}
44+
data <- x$get()
45+
inv <- solve(data, ...)
46+
x$setinv(inv)
47+
inv
1548
}

0 commit comments

Comments
 (0)