forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
40 lines (34 loc) · 1.38 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
## These functions help to avoid computing inverse matrices for the same input matrix
## several times during the task, we can just use the cashes inversed matrix every time
## This function cashes the inverse matrix of the input matrix and allows to change it or
## retrieve it whenever we need
makeCacheMatrix <- function(storedMatrix = matrix()) {
storedInverse <- NULL
setMatrix <- function(newMatrix) {
storedMatrix <<- newMatrix
storedInverse <<- NULL
}
getMatrix <- function() storedMatrix
setInverse <- function(solution) storedInverse <<- solution
getInverse <- function() storedInverse
list(setMatrix = setMatrix, getMatrix = getMatrix,
setInverse=setInverse,
getInverse = getInverse)
}
## The following function calculates the inverse of the input matrix
## However, it first checks to see if the inversed matrix has already been calculated.
## If so, it gets the storedInverse from cache and skips the computation
## Else it calculates the inverse of input matrix and sets the inversed matrix
## in the cache via the `setInverse` function.
cacheSolve <- function(x, ...) {
storedInverse <- x$getInverse()
if(!is.null(storedInverse)) {
message("getting cached data")
return(storedInverse)
}
data <- x$getMatrix()
storedInverse <- solve(data, ...)
x$setInverse(storedInverse)
storedInverse
}
## Return a matrix that is the inverse of 'x'