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
47 lines (43 loc) · 1.29 KB
/
cachematrix.R
File metadata and controls
47 lines (43 loc) · 1.29 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
## Programming assignment 2: Caching the Inverse of a Matrix
## Calculate inverse of a matrix, with caching calculated result.
##
## This file contains 2 companion functions:
## - makeCacheMatrix: get function vector used by cacheSolve.
## - cacheSolve: get inverse of a matrix. use with makeCacheMatrix.
##
## How to USE:
## x <- matrix(c(1,2,3,4), nrow=2, ncol=2)
## m <- makeCacheMatrix(x)
## cacheSolve(m) # first call
## cacheSolve(m) # second call, "getting cached data"
# create a vector of functions that:
# * get a matrix
# * set a matrix
# * set a inverse of the matrix
# * get a (cached) inverse of the matrix
makeCacheMatrix <- function(a = matrix()) {
ia <- NULL
setMatrix <- function(b) {
a <<- b
ia <<- NULL
}
getMatrix <- function() a
setInverseMatrix <- function(ib) ia <<- ib
getInverseMatrix <- function() ia
list(setMatrix = setMatrix, getMatrix = getMatrix,
setInverseMatrix = setInverseMatrix,
getInverseMatrix = getInverseMatrix)
}
# Return a matrix that is the inverse of 'm'
# This function assumes 'm' is invertible.
cacheSolve <- function(m, ...) {
cache_ia <- m$getInverseMatrix()
if(!is.null(cache_ia)){
message("getting cached data")
return(cache_ia)
}
a <- m$getMatrix()
ia <- solve(a,...)
m$setInverseMatrix(ia)
ia
}