forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachematrix.R
53 lines (38 loc) · 1.04 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
## Assignment: Caching the Inverse of a Matrix
## A function that returns a list containing functions to:
## - set the value of the matrix
## - get the value of the matrix
## - set the value of the matrix's inverse
## - get the value of the matrix's inverse
makeCacheMatrix <- function(x = matrix()) {
i <- NULL
# set new matrix and clear the inverse
set <- function(y) {
x <<- y
i <<- NULL
}
# return the matrix
get <- function() x
# set the inverse
setinverse <- function(inverse) i <<- inverse
# return the inverse
getinverse <- function() i
#Expose the methods
list(set = set, get = get, setinverse = setinverse, getinverse = getinverse)
}
## Calculates the inverse of matrix using the above function
cacheSolve <- function(x, ...) {
# get inverse
i <- x$getinverse()
#check if inverse already calculated
if(!is.null(i)) {
message("getting cached data")
return(i)
}
data <- x$get()
# calculate the inverse
i <- solve(data, ...)
#set inverse
x$setinverse(i)
i
}