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
57 lines (43 loc) · 1.23 KB
/
cachematrix.R
File metadata and controls
57 lines (43 loc) · 1.23 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
53
54
55
56
57
## Return Inverse of given Matrix
##
## Cache input matrix.
makeCacheMatrix <- function(x = matrix()) {
# initiallise inversed matrix.
iv <- NULL
# get and set original matrix
set <- function(y) {
# Do not set the same matrix again.
if(!matrixEqual(x, y)){
x <- y
iv <<- NULL
}
}
get <- function() x
#get and set inversed matrix.
setInverse <- function(inverse) iv <<- inverse
getInverse <- function() iv
#return construction list
list( set = set, get = get, setInverse = setInverse, getInverse = getInverse)
}
## Inverse and return inversed matrix
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
iv <- x$getInverse()
#If inversed matrix was cached, return it.
if (!is.null(iv)) {
return (iv)
}
#get original set matrix
data <- x$get()
#actual work
iv <- solve(data)
#cache the inversed matrix.
x$setInverse(iv)
#return inversed matrix
iv
}
#Compare two matrix,
#they are identical if both dimensions and values are equal.
matrixEqual <- function(m1, m2){
is.matrix(m1) && is.matrix(m2) && dim(m1) == dim(m2) && all(m1 == m2)
}