forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
55 lines (41 loc) · 1.64 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
## These two functions store a matrix, calculuate its inverse, and store this inverse
##for later use
#function which takes a matrix x as input, and stores this matrix, as well as the inverse if calculated
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
#define function which stores the new matrix in set, and initilizes the inverse to NULL
#across all environments (e.g., if there is an old m hanging around elsewhere get rid of # it)
set <- function(y) {
x <<- y
m <<- NULL
}
#define function which retrieves the matrix
get <- function() x
#define function which stores an input inverse of x
# use <<- operator to assign an input value of "solve" to m
setinv <- function(solve) {m <<- solve}
#define function which retrieves the stored inverse of x
getinv <- function() m
#return list object of these functions
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
#function to calculate the inverse of a matrix, if that inverse does not already exist #in the stored values from makeCacheMatrix
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
#check if inverse previously calculated, if not then move on to calculate
# if yes (!is.null is true), then retrieve cached invserse
m <- x$getinv()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
#retrieve the matrix
data <- x$get()
#matrix inverse calculation
m <- solve(data, ...)
#assign the inverse to setinv
x$setinv(m)
m
}