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
70 lines (65 loc) · 1.87 KB
/
Copy pathcachematrix.R
File metadata and controls
70 lines (65 loc) · 1.87 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
## cachematrix.R
##
## Build a list of function to maintain matrix and its inverse cache.
## It's helpful while dealing with repeat inverse calculation on the
## same matrix.
##
## Example:
## M <- matrix(1:4, nrow=2, ncol=2)
## cacheMatrix <- makeCacheMatrix(M)
## inverse <- cacheSolve(cacheMatrix)
##
## cacheMatrix$set(M) # chang the original matrix.
## M <- cacheMatrix$get() # get the original matrix.
##
## Build up a list object that contains functions
## for maintenaning matrix x and the cache of
## its inverse.
##
## Params: x a matrix object
## Return: list object, containning set, get,
## setinverse, getinverse functions
makeCacheMatrix <- function(x = matrix()) {
## Initial: NOT CACHED YET.
inv <- NULL
## Function for changging matrix.
set <- function(y) {
## Change to a new matrix.
x <<- y
## The cache should be invalidated.
inv <<- NULL
}
## Function for getting original matrix.
get <- function() x
## Function for setting inverse matrix for cache.
setinverse <- function(inverse) inv <<- inverse
## Function for getting cached inversed matrix.
## If not yet cached, return null.
getinverse <- function() inv
## Put all the functions together
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## Return a matrix that is the inverse of 'x'
## If the inverse is already calculated, return
## from the cache. Otherwise pass to solve() function.
##
## Params: x the matrix needed to be inversed
## Return: The inversed matrix of x.
cacheSolve <- function(x, ...) {
## Reading from cache.
inv <- x$getinverse()
## Check if already cached.
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
## Get original matrix.
data <- x$get()
## Really calculate the inverse.
inv <- solve(data, ...)
## Cache the result.
x$setinverse(inv)
inv
}