forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
64 lines (50 loc) · 2.33 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
63
64
## This function creates four separate functions that are stored in a list that when accessed
## will create a matrix, solve for it's inverse, and then cache both in the global environment
## the four functions in the list are as follows:
## 1. set: assigns the provided matrix as a cached global variable
## 2. get: returns the cached matrix of the set function
## 3. setinv: creates an inverse matrix and stores it as a cached global variable
## 4. getinv: returns the cached inverse matrix
makeCacheMatrix <- function(x = matrix()) {
## define "inv" as NULL within the scope of the function, this variable will later be used
## to store the inverse matrix
inv <- NULL
## create a function to assign the matrix provided to the variable "x"
## in the parent environment of the makeCacheMatrix() function
## as opposed to the current environment of the set() function
set <- function(y) {
x <<- y
inv <<- NULL
}
## create a function that will return the matrix stored in "x"
get <- function() x
## assign the inverse matrix "z" to the inv variable within the parent environment
setinv <- function(z) inv <<- z
## return the invese matrix object stored in the variable "inv"
getinv <- function() inv
##create a list of all the functions for setting and getting matrix and inverse matrix
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
## This function first tests for the existance of a cached inverse matrix which is returned if
## it exists, otherwise it creates an inverse matrix and caches it using
# the four functions created by makeCacheMatrix
cacheSolve <- function(x, ...) {
## use the getinv() function from makeCacheMatrix function to retrieve the
## inverse generated by the setinv() function
inv <- x$getinv()
## if the variable "inv" already contains a cached inverse matrix, return the inverse matrix
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
## otherwise create an inverse matrix by first retrieving the cached matrix with get()
## then solving for the inverse with the solve() function
## store the solution inverse matrix in the "inv" variable using the function setinv()
## then return the inverse matrix stored in the "inv" variable
data <- x$get()
inv <- solve(data, ...)
x$setinv(inv)
inv
}