forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
55 lines (39 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
## Functions that cache the inverse of a matrix
## Create a special matrix object for caching the value of the inverse,
## with setter and getter for both matrix and inverse
makeCacheMatrix <- function(x = matrix()) {
# Field for containing the invese of the matrix
inverse <- NULL
# Function for setting the value of the matrix
set <- function(y) {
x <<- y
inverse <<- NULL
}
# Function for getting the value of the matrix
get <- function() x
# Function for setting the inverse of the matrix
setinverse <- function(setInverse) {
inverse <<- setInverse
}
# Function for get the inverse
getinverse <- function() inverse
# Return a list of all the above functions
list(set = set, get = get, setinverse = setinverse, getinverse = getinverse)
}
## Compute the inverse of the matrix returned by the previous function.
## If the inverse has already been calculated, then the function
## should retrieve the cached value of the inverse.
cacheSolve <- function(x, ...) {
inverse <- x$getinverse()
# Check if there is the cached inverse of teh matrix
if(!is.null(inverse)) {
message("getting cached inverse")
return(inverse)
}
# If not compute the inverse and cache the value
matrix <- x$get()
inverse <- solve(matrix, ...)
x$setinverse(inverse)
## Return a matrix that is the inverse of 'x'
inverse
}