forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
52 lines (44 loc) · 1.41 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
## These two functions are almost identical to what's in the example of calculating
## mean of a vector and save the result
## The functions take an invertible matrix (there's no check in place to ensure the
## matrix provided is invertible) and do the inversion, using R solve() function, and
## save the result in a different environment as cache, for future references
## this exercise is to demonstrate R lexical scoping.
## R use variables where function is defined.
## to call it, use
## source("cachematrix.R")
## a<-matrix(c(1,2,-2,1),2,2)
## cacheSolve(makeCacheMatrix(a))
## while a is an invertible matrix
## Create a list of 4 functions, set, get, setsolve, getsolve
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
## save in a different environment
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
## store in a different environment
setsolve <- function(solve) m <<- solve
getsolve <- function() m
## create a list of functions
list(set = set, get = get,
setsolve = setsolve,
getsolve = getsolve)
}
## inverse the matrix. If the inversion exists, use it, to save computation time
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x', that's cached
m <- x$getsolve()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
## if not exists, inverse
data <- x$get()
m <- solve(data, ...)
## save the inversion of 'x'
x$setsolve(m)
m
}