Skip to content

Commit 413cd76

Browse files
committed
Update cachematrix.R
1 parent e4eed41 commit 413cd76

File tree

1 file changed

+46
-9
lines changed

1 file changed

+46
-9
lines changed

cachematrix.R

Lines changed: 46 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,52 @@
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+
## A pair of functions that cache the inverse of a matrix.
52

3+
## This function creates a special "matrix" object that can cache its inverse.
64
makeCacheMatrix <- function(x = matrix()) {
7-
5+
# the inverse of the matrix
6+
inverse <- NULL
7+
8+
# set the matrix
9+
set <- function(newMatrix) {
10+
x <<- newMatrix
11+
x <<- NULL
12+
}
13+
14+
# get the matrix
15+
get <- function() {
16+
x
17+
}
18+
19+
# set the inverse
20+
setInverse <- function(inv) {
21+
inverse <<- inv
22+
}
23+
24+
# get the inverse
25+
getInverse <- function() {
26+
inverse
27+
}
28+
29+
# return special "matrix" object
30+
list(set=set, get=get, setInverse=setInverse, getInverse=getInverse)
831
}
932

10-
11-
## Write a short comment describing this function
12-
33+
## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above.
1334
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
35+
# get cached value of matrix inverse
36+
inverse <- x$getInverse()
37+
38+
# if it's not null, return it
39+
if (!is.null(inverse)) {
40+
message("getting cached inverse")
41+
return(inverse)
42+
}
43+
44+
# otherwise we need to calculate it
45+
inverse <- solve(x$get())
46+
47+
# then cache it
48+
x$setInverse(inverse)
49+
50+
# return the inverse
51+
inverse
1552
}

0 commit comments

Comments
 (0)