forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
68 lines (62 loc) · 1.54 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
68
# This function returns list of functions.
# Purpose of this function is to store matrix x and its inverse
# list contains following fuctions
# * set - set matrix
# * get - get matrix
# * setInverse - set inverse of matrix
# * getInverse - get inverse of marrix
# e.g
# y<-makeCacheMatrix(matrix(1:9, 3, 3))
# y$get()
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 2 5 8
# [3,] 3 6 9
makeCacheMatrix <- function(x = matrix()) {
inverse<-NULL # to hold inverse of matrix
# set matrixt
set<- function(m){
x<<-m
inverse<-NULL
}
# return the matrix
get<-function() x
# set inverse
setInverse<-function(inv) inverse<<-inv
# return inverse
getInverse<-function() inverse
list(get=get, set=set,
getInverse=getInverse, setInverse=setInverse)
}
# 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 returns the inverse from the cache
# e.g.
# > m<-matrix(1:4,2,2)
# > m1<-makeCacheMatrix(m)
# > cacheSolve(m1)
# compute inverse
# [,1] [,2]
# [1,] -2 1.5
# [2,] 1 -0.5
# > cacheSolve(m1)
# return cached value
# [,1] [,2]
# [1,] -2 1.5
# [2,] 1 -0.5
#
cacheSolve <- function(x, ...) {
# Return a matrix that is the inverse of 'x'
inverse<-x$getInverse()
if(!is.null(inverse)){
message("return cached value")
return(inverse)
}
m<-x$get()
# computes inverse
inverse<-solve(m)
#update cache
message("compute inverse")
x$setInverse(inverse)
inverse
}