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
52 lines (40 loc) · 1.68 KB
/
cachematrix.R
File metadata and controls
52 lines (40 loc) · 1.68 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
## First function is used to provide cache methods for inverse of a matrix
## Second function is used to access cache or calculation of inverse of matrix
## makeCacheMatrix provides four methods to set and get the inout values and set and
# get the inverse of a matrix
makeCacheMatrix <- function(x = matrix()) {
inverseMatrix <- NULL
# set method for input
setInput <- function(y) {
x <<- y
inverseMatrix <<- NULL
}
# get method for inout
getInput <- function() {
x
}
# set method for inverse
setInverse <- function(inverse_matrix) {
inverseMatrix <<- inverse_matrix
}
# get method for inverse
getInverse <- function() {
inverseMatrix
}
list(setInput = setInput, getInput = getInput, setInverse = setInverse, getInverse = getInverse)
}
## This function uses the list output created by makeCacheMatrix function as its input
## using getInverse function from makeCacheMatrix function it first checks if the inverse
## is calculated or not. If yes, it is read from get method else inverse is calculated.
## This calculated inverse is then set into makeCacheMatrix function for caching
cacheSolve <- function(x, ...) {
inverseOfMatrix <- x$getInverse()
if(!is.null(inverseOfMatrix)) {
print("Inverse from cached data")
return(inverseOfMatrix)
}
input_data <- x$getInput()
inverseOfMatrix <- solve(input_data)
x$setInverse(inverseOfMatrix)
return(inverseOfMatrix)
}