forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
62 lines (48 loc) · 1.37 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
## The functions included below can be used to cache the inverse of a matrix
## makeCacheMatrix creates a matrix object that can cache its inverse
makeCacheMatrix <- function(x = matrix()) {
## initialize inverse
inv <- NULL
## setter method
set <- function( matrix ) {
mat <<- matrix
inv <<- NULL
}
## getter method
get <- function() {
## return matrix
mat
}
## inverse setter method
setInverse <- function(inverse) {
inv <<- inverse
}
## inverse getter method
getInverse <- function() {
## return inverse
inv
}
## retrun list with the methods
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## cacheSolve computes the inverse of the matrix returned by makeCacheMatrix
## cacheSolve will the inverse from its cache if it has already been calculated
cacheSolve <- function(x, ...) {
## meturn inverse matrix of x
mat <- x$getInverse()
## retrun inverse if already calculated
if( !is.null(mat) ) {
message("getting cached data")
return(mat)
}
## get the matrix from object
matrix_data <- x$get()
## calculate the inverse
mat <- solve(matrix_data) %*% matrix_data
## set inverse to object
x$setInverse(mat)
## return matrix
mat
}