Skip to content

Commit 15ee147

Browse files
committed
both functions
1 parent 006ceee commit 15ee147

File tree

1 file changed

+40
-4
lines changed

1 file changed

+40
-4
lines changed

cachematrix.R

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

4-
## Write a short comment describing this function
4+
## Creates a special type of matrix object, called a CacheMatrix,
5+
## which can cache its inverse matrix.
56

67
makeCacheMatrix <- function(x = matrix()) {
7-
8+
cacheMatrix <- NULL
9+
inverseMatrix <- NULL
10+
11+
set <- function(aMatrix) {
12+
cacheMatrix <<- aMatrix
13+
inverseMatrix <<- NULL
14+
}
15+
16+
get <- function() x
17+
18+
setInverse <- function(inverse) inverseMatrix <<- inverse
19+
20+
getInverse <- function() inverseMatrix
21+
22+
list(set = set, get = get,
23+
setInverse = setInverse,
24+
getInverse = getInverse)
25+
826
}
927

1028

11-
## Write a short comment describing this function
12-
29+
## Computes the inverse of a CacheMatrix, which is a matrix returned by makeCacheMatrix.
30+
## If the matrix has not changed since the last call to cacheSolve, a cached copy of
31+
## the inverse matrix will be returned, otherwise the inverse is computed, cached
32+
## and returned.
33+
##
34+
## PreCondition: The matrix, x, is invertible
1335
cacheSolve <- function(x, ...) {
1436
## Return a matrix that is the inverse of 'x'
37+
38+
inv <- x$getInverse()
39+
if (!is.null(inv)) {
40+
message("getting cached data")
41+
return(inv)
42+
}
43+
44+
# get the inverse
45+
data <- x$get()
46+
inv <- solve(data)
47+
48+
x$setInverse(inv) # cache inv
49+
50+
inv # returns inv
1551
}

0 commit comments

Comments
 (0)