forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachematrix.R
67 lines (54 loc) · 1.69 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
67
# Calculating inverse matrix is costly process, here two functions are provided
# to cache and retrieve inverse matrix.
# Create a special version of a invertiable matrix that can cache its inverse.
#
# Args:
# x: a invertiable matrix to be stored. Default to an empty matrix.
#
# Returns:
# a list which contains a set of methods for get/set invertiable matrix
# and get/set inverted version the matrix
#
# Note:
# If the original matrix is modified, its cached inverse matrix will be cleared
makeCacheMatrix <- function(x = matrix()) {
matrixInverse <- NULL
# modify original matrix
set <- function(y) {
x <<- y
matrixInverse <<- NULL
}
# get original matrix
get <- function() x
# cache the inverse version of the original matrix
setInverse <- function(inverse) matrixInverse <<- inverse
# get the cached inverse matrix
getInverse <- function() matrixInverse
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
}
# Calculate the inverse of a matrix and retrieve cached version if its already calculated
#
# Args:
# x: a special version of the matrix generated by calling makeCacheMatrix
#
# Returns:
# Inverse of the input matrix
#
# Note:
# This method assumes that the input matrix is always invertiable
cacheSolve <- function(x, ...) {
# get cached version of the inverse matrix
matrixInverse <- x$getInverse()
# check whether it is already cached
if (!is.null(matrixInverse)) {
message("Retrieved cached data")
return(matrixInverse)
}
# get the original matrix
matrixData <- x$get()
# calculate inverse matrix
matrixInverse <- solve(matrixData, ...)
# cache inverse matrix result
x$setInverse(matrixInverse)
matrixInverse
}