forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachematrix.R
53 lines (40 loc) · 1.89 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
## This is a description to two functions, whose details are broken down into two, below.
## functions: makeCacheMatrix; this function encapsulates a couple of functions that are then called by the second function
makeCacheMatrix <- function(x = matrix()) {
## we receive our matrix, set the value of m (the soon to be used cached value, to nothing
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
## here, we initialize all the functions we will need to us
## we also cache the value given to m, by getinverse(), using the function setinverse()
get <- function() x
setinverse <- function(solve) m <<- solve
getinverse <- function() m
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## function: cacheSolve ; this function checks if the matrix inverse has been calculated,
## if yes, it returns a cached value, if no, it solves the matrix inverse and caches it accordingly
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
## the cacheInverse function checks first is there is any value in m, which is the variable assigned to the calculated and cached inverse
## we use the getinverse() function to pick the "cached" value, that is if its been cached
cacheInverse <- function(x, ...) {
m <- x$getinverse()
## if m is null, then this is the first time we are doing the calculations, so we get to work, calculating the inverse
## if m is not null, we prompt the user that we are showing a cached value, and we show the value of m
if(!is.null(m)) {
message("getting cached inverse for the matrix")
return(m)
}
## in this case, m was null, so we are getting the matrix and calculating its inverse.
## we then set the value of m, by calling the setinverse() function which actually caches the value using the <<- sign
data <- x$get()
m <- solve(data, ...)
x$setinverse(m)
m
}
}