forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
44 lines (40 loc) · 1.33 KB
/
cachematrix.R
File metadata and controls
44 lines (40 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
## The following functions provide a way to create a special
## matrix object which can cache internally its inverse.
# Create object containing a list of functions to
# set and get the matrix. It also implements
# functions to set and get its inverse, which
# will be used as the cache by the cacheSolve function below
makeCacheMatrix <- function(x = matrix()) {
invMatrix <- NULL
#Set matrix and reset cache
set <- function(m) {
x <<- m
invMatrix <- NULL
}
#Get matrix
get <- function() x
#Get the cached inverse matrix
getInverse <- function() invMatrix
#Set the cached inverse matrix
setInverse <- function(inv) {
invMatrix <<- inv
}
#Return the list of implemented functions
list(set=set, get=get, getInverse=getInverse, setInverse=setInverse)
}
# Return the inverse of a matrix, checking if it's already cached first
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inverse <- x$getInverse()
if (!is.null(inverse)) {
message("Returning inverse matrix cached.")
return(inverse)
}
#Otherwise we need to compute the inverse and store
# the result in the cache
originalMatrix <- x$get()
inverse <- solve(originalMatrix)
x$setInverse(inverse)
#Now return the inverse
inverse
}