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
74 lines (54 loc) · 1.73 KB
/
Copy pathcachematrix.R
File metadata and controls
74 lines (54 loc) · 1.73 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
## makeCacheMatrix creates a function that can cache the
## matrix and the inverse.
## Function contain a list the a set and get for both the matrix
## and inverse matrix.
makeCacheMatrix <- function(x = matrix()) {
## initialize the inverse matrix value
i <- NULL
## set the value of the matrix
set <- function(y) {
x <<- y
i <<- NULL
}
## get the value of the martix
get <- function() {
x
}
## set the value for the inverse matrix
setInverse <- function(inverse) {
i <<- inverse
}
## get the value for the inverse matrix
getInverse <- function() {
i
}
## return a list of all get and set functions
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## The cacheSolve function calculates the inverse of a matrix.
## A check is made to see if the inverse has already been calculated.
## If the inverse is already calculated the cached copy is used and the
## computation is skipped.
## Otherwise, the solve function is used to calculate the inverse of the
## matrix and a stored value is set in the cache.
cacheSolve <- function(x, ...) {
## get the inverse of x
i <- x$getInverse()
## check that the returned inverse for x is not null
if(!is.null(i)) {
message("getting cached data")
## if not null return the cached inverse and exit
return(i)
}
## inverse does not exist
## get the matrix
i <- x$get()
## calculate the inverse with solve
m <- solve(x, ...)
## set the inverse for future use
x$setInverse(i)
## return the calculated inverse end exit
i
}