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
62 lines (54 loc) · 2.06 KB
/
cachematrix.R
File metadata and controls
62 lines (54 loc) · 2.06 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
# This module contains functions for memoization (caching) of results
# on an associated matrix.
# makeCacheMatrix(src_matrix) wraps the src_matrix with an object that
# can cache the values of computations on the matrix.
#
# Sample usage, finding the transpose and inverse of a matrix:
#
# x <- makeCacheMatrix(matrix(c(3,0,2,1,5,3,9,2,1),nrow=3))
# x_transpose <- x$cacheGet("t", t)
# x_inverse <- cacheSolve(x)
#
makeCacheMatrix <- function(src_matrix = matrix()) {
# Create an environment, which can store keys and the corresponding
# cached values.
cache_store <<- new.env()
# Overwrite the existing matrix with new_value
set <- function(new_value) {
src_matrix <<- new_value
cache_store <<- new.env()
}
# Retrieve the current matrix
get <- function() src_matrix
# Return the value associated with the given key. If the value is not
# available in the cache, it is generated by calling the passed
# calc_function, and will be returned from the cache thereafter.
#
# If called with no calc_function, a value is only returned if it's
# already in the cache.
cacheGet <- function(key, calc_function =NULL) {
# Check for a cached value, and either use it or calculate and cache.
if (exists(key, envir=cache_store, inherits=FALSE)) {
# Because we define a get() function above, I have to call the
# built-in get() using the base environment.
cache_value <- baseenv()$get(key, envir=cache_store)
} else {
# If the value was not cached and we can calculate it, do so and
# cache it.
# print("Calling function to store in cache")
if (!is.null(calc_function)) {
cache_value <- calc_function(get())
assign(key, cache_value, envir=cache_store)
} else {
cache_value <- NULL
}
}
return (cache_value)
}
list(set = set, get = get, cacheGet = cacheGet)
}
# The cacheSolve() takes a matrix created by makeCacheMatrix(),
# and cache the result to be used on future invocations.
cacheSolve <- function(cache_matrix) {
cache_matrix$cacheGet("solve", solve)
}