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
83 lines (66 loc) · 2.42 KB
/
cachematrix.R
File metadata and controls
83 lines (66 loc) · 2.42 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
## This set of functions allows the inverse of a matrix
## to be found quickly by caching the inverse. The inverse
## is only calculated if it has not already been calculated,
## thus eliminating repetitive calculations of the inverse
## of the same matrix.
## This function returns a list of four functions given a
## argument that is a matrix. These functions include get
## and set to get and set the matrix itself. They also include
## getInverse to obtain the inverse of the matrix and setInverse
## to cache the inverse of the matrix.
##
## @param x a matrix
## @return a list of functions get, set, getInverse, setInverse
makeCacheMatrix <- function(x = matrix()) {
inverse <- NULL
## set the data x to the new data y and clear the stored
## inverse since it has not been calculated yet for the new data.
##
## @param y the new matrix to be stored
set <- function(y) {
x <<- y
inverse <<- NULL
}
## return the matrix x
##
## @return x the matrix x
get <- function() x
## set the stored inverse to the calculated inverse.
##
## @param newInverse the calculated inverse of the matrix x
setInverse <- function(newInverse) inverse <<- newInverse
## return the stored inverse of the matrix x
##
## @return inverse the stored inverse
getInverse <- function() inverse
## generate the list containing the functions
## get, set, getInverse, and setInverse.
## This list is returned.
list(set = set, get = get, getInverse = getInverse, setInverse = setInverse)
}
## This function returns the inverse of a matrix. It takes an
## argument of type list as generated by the function makeCacheMatrix.
## If the inverse of the matrix has not been calculated, the inverse
## is calculated and cached. Otherwise the cached inverse is returned.
## This enables the inverse of a matrix to be found quickly and eliminates
## multiple calculations of the inverse of the same matrix.
##
## @param list(get, set, getInverse, setInverse)
## @return inverse the inverse of the matrix in the list
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
## Get the stored inverse of the matrix
inverse <- x$getInverse()
## Calculate the inverse if it has not been calculated yet
if (is.null(inverse)) {
message("Calculating inverse")
## Get the data
matrixX <- x$get()
## Calculate the inverse
inverse <- solve(matrixX)
## Cache the inverse
x$setInverse(inverse)
}
## return the inverse
inverse
}