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
60 lines (48 loc) · 1.85 KB
/
cachematrix.R
File metadata and controls
60 lines (48 loc) · 1.85 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
## Functions for caching a matrix and its inverse
## Input: an N X N square, numeric, invertible Matrix
## in keeping with assignment directions, proper input
## is assumed
## Returns: a matrix object for a square numeric matrix with four
## methods
## set: sets the matrix
## get: sets the matrix
## set_inverse: sets the matrix
## get_inverse: sets the matrix
makeCacheMatrix <- function(x = matrix()) {
## initialize the matrix inverse
my_inverse <- NULL
## create a function for storing a new matrix
set <- function(y) {
x <<- y
my_inverse <<- NULL
}
## get the matrix
get <- function() x
## stores the matrix inverse, which is calculated elsewhere
set_inverse <- function(new_inverse) my_inverse <<- new_inverse
## get the inverse previously calculated
get_inverse <- function() my_inverse
## return the four functions above
list(set = set, get = get, set_inverse = set_inverse,
get_inverse = get_inverse)
}
## Input: A matrix object created by makeCacheMatrix()
## Matrix assumed to be numeric, square, and invertible
## Returns: The inverse of the matrix.
## If the inverse already calculated, it is returned from cache
## Otherwise, calculated, stored, and returned
## Writes message to screen when getting cached data
cacheSolve <- function(x, ...) {
# get the inverse: either NULL, if not calculated, or a cached
# version of the inverse
my_inverse <- x$get_inverse()
# if inverse already calculated, return it
if (!is.null(my_inverse)) {
message("getting cached data")
return(x$get_inverse())
}
# Cache the calculated inverse
x$set_inverse(solve(x$get()))
# return the inverse
x$get_inverse()
}