forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
67 lines (51 loc) · 1.99 KB
/
Copy pathcachematrix.R
File metadata and controls
67 lines (51 loc) · 1.99 KB
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
65
66
67
## File cachematrix.R
## Functions
## 1. makeCacheMatrix
## 2. cacheSolve
## The above functions compute and cache the inverse of a matrix.
## Repeated calls return the cached results without recomputing.
## Function makeCacheMatrix build and returns a list with functions
## 1. setMatrix - set the value of the matrix
## 2. getMatrix - get the value of the matrix
## 3. setInverseMatrix - set the inverse of the matrix in parent(global) environment
## 4. getInverseMatrix - get the inverse of matrix if availble in the parent
## environment else return NULL.
makeCacheMatrix <- function(x = matrix()) {
inverse <- NULL
## set matrix
setMatrix <- function(y) {
x <<- y
inverse <<- NULL
}
## return matrix
getMatrix <- function() x
## set cache inverse
setInverseMatrix <- function(inv) {
inverse <<- inv
}
## return cache inverse
getInverseMatrix <- function() inverse
list(setMatrix = setMatrix,
getMatrix = getMatrix,
setInverseMatrix = setInverseMatrix,
getInverseMatrix = getInverseMatrix)
}
## Function cacheSolve solves the matrix in makeCacheMatrix and returns its inverse
## It checks if the inverse is in cache. Else it computes and stores in cache
## Subsequent calls return the inverse from the cache
cacheSolve <- function(x, ...) {
## Retrieve a matrix that is the inverse of 'x' from cache
inverse <- x$getInverseMatrix()
## if value in cache is null compute inverse and store in cache
if(is.null(inverse)) {
message("adding new matrix to cache")
matrix <- x$getMatrix()
inverse <- solve(matrix, ...)
x$setInverseMatrix(inverse)
}
else {
message("getting inverse from cache")
}
## inverse returned from cache or added to cache and returned
inverse
}