forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
47 lines (37 loc) · 1.14 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
#12/22/2016
#This program will store a inverse of a matrix if it is already calculated
#so that when we want to calculate the inverse of the same matrix that has already been
#calculated previously, it won't recalculate
#Instead, it will get from the cache
#Otherwise, it will calculate and again store in in cache
#This function will store the matrix and provides methods to get,set the matrix itself and the inverse of it
makeCacheMatrix <- function(x = matrix()){
inverse<<-NULL
set <- function(y){
x<<-y
inverse<<-NULL
}
get <- function(){
return(x)
}
setInverse <- function(){
inverse<<-solve(x)
}
getInverse <- function(){
return(inverse)
}
list(set=set,get=get,setInverse=setInverse,getInverse=getInverse) #returns a special vector
}
#This function first searches in the cache, of found displays the value,
#otherwise calculate the inverse and then saves into the cache for later use
cacheSolve <- function(x, ...){
inv <- x$getInverse()
if(!is.null(inv)){
message("getting cached data")
return(inv)
}
data<-x$get()
newInverse <- solve(data)
x$setInverse()
return(newInverse)
}