forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachematrix.R
58 lines (45 loc) · 2.4 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
## Functions used to use cache to store matrices and their inverse to avoid recalculation.
## makeCacheMatrix initialises a group of functions to perform these tasks based on
## an invertible matrix based to it. cacheSolve() then uses these functions to return the inverted matrix
## (from cache if available) when passed the group of functions.
## makeCacheMatrix returns a list containing 4 functions to
## set and retrieve in cache the matrix passed to the function and its inverse.
makeCacheMatrix <- function(cached_matrix = matrix()) {
cached_inverse <- NULL
# function to set the cached matrix to be the value passed to it
# and reset the cached_inverse to NULL.
setMatrix <- function(y) {
cached_matrix <<- y
cached_inverse <<- NULL
}
# function to return the cached value x.
getMatrix <- function() cached_matrix
# function to cache the value passed to it as the cached_inverse
setInverse <- function(x) cached_inverse <<- x
# function to return the cached inverse.
getInverse <- function() cached_inverse
# return a list containing the 4 functions.
list(setMatrix = setMatrix, getMatrix = getMatrix,
setInverse = setInverse,
getInverse = getInverse)
}
## cacheSolve() takes list of functions generated by makeCacheMatrix() as an argument.
## it then uses getInverse (one of the functions) to see if an inverted matrix has already been cached.
## If so, it will return the cached value (i.e. the inverse of the matrix passed to makeCacheMatrix() to create the functions)
## If not, it will create the inverse itself by calling the original matrix from cache using getMatix()
## then calculating the inverse using setMatrix()
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
# retrieve the inverted matrix from cache.
my_inverse <- x$getInverse()
# if my_inverse has been defined (i.e. cached already) return it
if(!is.null(my_inverse)) {
message("getting cached data")
return(my_inverse)
}
# otherwise calculate, cache and return the inverse.
invertible_matrix <- x$getMatrix()
my_inverse <- solve(invertible_matrix, ...)
x$setInverse(my_inverse)
my_inverse
}