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.53 KB
/
cachematrix.R
File metadata and controls
60 lines (48 loc) · 1.53 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
## Andrew Freisthler
## Coursera R Programming - September 2014
## The two functions below, makeCacheMatrix and cacheSolve work together
## to lesson the impact of the computationally intensive operation of
## computing the inverse of a matrix if it has already been computed.
##
## Example Usage (second call to cacheSolve would not require recalculating):
## source("./cachematrix.R")
## m <- matrix(rnorm(100),10,10)
## cm <- makeCacheMatrix(m)
## cacheSolve(cm)
## cacheSolve(cm)
##
## makeCacheMatrix creates a special 'matrix', which is really a list containing methods:
## 1) set the value of the matrix
## 2) get the value of the matrix
## 3) set the value of the solve
## 4) get the value of the solve
makeCacheMatrix <- function(x = matrix()) {
cachedSolve <- NULL
set <- function(y) {
x <<- y
cachedSolve <<- NULL
}
get <- function() {
x
}
setSolve <- function(solve) {
cachedSolve <<- solve
}
getSolve <- function() {
cachedSolve
}
list(set = set, get = get, setSolve = setSolve, getSolve = getSolve)
}
## cacheSolve returns the output of solve if it has already been calculated, otherwise it
## calculates and then stores it.
cacheSolve <- function(x, ...) {
solveFromCache = x$getSolve()
if(!is.null(solveFromCache)) {
message("getting cached data")
return(solveFromCache)
}
data <- x$get()
solveToCache <- solve(data, ...)
x$setSolve(solveToCache)
solveToCache
}