forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachematrix.R
67 lines (52 loc) · 2.23 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# ===============================================================================================
# ===============================================================================================
# ===============================================================================================
# makeCacheMatrix function creates a special "matrix" object that can cache its inverse
# It contains a list of functions as follow:
# set the value of the input matrix
# get the value of the input matrix
# set the value of the inverse matrix
# get the value of the inverse matrix
makeCacheMatrix <- function(x = matrix()) {
# initialize inverse matrix
inv <- NULL
# set matrix value
set <- function(y) {
x <<- y
inv <<- NULL
}
# get matrix value
get <- function() x
# set inverse matrix
setinv <- function(inv_) inv <<- inv_
# get inverse matrix
getinv <- function() inv
# list of all functions
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
# ===============================================================================================
# ===============================================================================================
# ===============================================================================================
# This function computes the inverse of the special "matrix" returned by makeCacheMatrix above.
# If the inverse has already been calculated (and the matrix has not changed), then the cachesolve
# should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) {
# if the inverse is already exist then cache
inv <- x$getinv()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
data <- x$get()
# Calculate inverse matrix using solve function
inv <- solve(data, ...)
# cache that inverse matrix
x$setinv(inv)
# return
inv
}
# ===============================================================================================
# ===============================================================================================
# ===============================================================================================