Skip to content

Commit 3ae1be5

Browse files
author
Aaron Brady
committed
homework assignment solution
1 parent 7f657dd commit 3ae1be5

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

cachematrix.R

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,33 @@
11
## Put comments here that give an overall description of what your
22
## functions do
33

4-
## Write a short comment describing this function
5-
4+
## Creates a matrix that will cache its inverse, a costly operation
65
makeCacheMatrix <- function(x = matrix()) {
7-
6+
inv <- NULL
7+
list(
8+
set = function (y) {
9+
x <<- y
10+
inv <<- NULL
11+
},
12+
get = function() x,
13+
setInv = function(new_inv) inv <<- new_inv,
14+
getInv = function() inv
15+
)
816
}
917

10-
11-
## Write a short comment describing this function
12-
18+
# Find the inverse of the passed matrix and return it and cache it in the passed param
19+
# note that x must be a value returned from 'makeCachedMatrix'
20+
# The following function calculates the inverse of the special matrix
21+
# created with 'makeCachedMatrix' However, it first checks to see if the
22+
# inverse has already been calculated. If so, it gets the inverse from the
23+
# cache and skips the computation. Otherwise, it calculates the inverse of
24+
# the matrix and sets the value using the setInv function on x
1325
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
26+
inv <- x$getInv()
27+
if (!is.null(inv)) {
28+
return(inv)
29+
}
30+
inv <- solve(x$get())
31+
x$setInv(inv)
32+
inv
1533
}

0 commit comments

Comments
 (0)