forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
60 lines (49 loc) · 1.46 KB
/
cachematrix.R
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
## R Programming - Assigment 2
##
## Adalberto Cubillo
##
## These functions will make a custom cached matrix component
## and will calculate the first time (if the matrix doesn't change) the inverse of the matrix.
## or return the cached one if re-executed with the same data.
## Makes a custom matrix capable of caching the inverse of it.
makeCacheMatrix <- function(matrix = matrix()) {
cachedInverseMatrix <- NULL
# Set the custom matrix data.
set <- function(newMatrix) {
matrix <<- newMatrix
cachedInverseMatrix <<- NULL
}
# Get the custom matrix data.
get <- function() {
matrix
}
# Set the inverse matrix.
setInverse <- function(inverseMatrix) {
cachedInverseMatrix <<- inverseMatrix
}
# Return the cached inverse matrix or NULL.
getInverse <- function() {
cachedInverseMatrix
}
# List the special methods for caching the inverse matrix.
list(set = set,
get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## Will return the cached matrix
##or calculate the inverse the first time (if the matrix doesn't change).
cacheSolve <- function(x, ...) {
inverse <- x$getInverse()
# Return the cached inverse matrix.
if (!is.null(inverse)) {
message("Getting cached inverse matrix.")
return(inverse)
}
# Calculate and store the inverse matrix.
data <- x$get()
inverse <- solve(data, ...)
x$setInverse(inverse)
# Return the inverse matrix.
inverse
}