forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
46 lines (41 loc) · 1.27 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
## Make cache matrix provides a wrapper to R internal matrix that supports manual caching of
## matrix inversion
## Provide a matrix to this wrapper class which can manually cache matrix inverse
## and will invalidate cache when set is called
makeCacheMatrix <- function(matrixInternal = matrix()) {
cachedInverse <- NULL
set <- function(m) {
matrixInternal <<- m
cachedInverse <<- NULL
}
get <- function() {
matrixInternal
}
setCachedInverse <- function (inverseOfMatrix) {
cachedInverse <<- inverseOfMatrix
}
getCachedInverse <- function () {
cachedInverse
}
list(get=get, set=set, setCachedInverse=setCachedInverse, getCachedInverse=getCachedInverse)
}
## provided a makeCacheMatrix, cacheSolve will return a cached inverse if it has been computed
## and if not will compute and cache using makeCacheMatrix
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
cachedInverse = x$getCachedInverse()
if (!is.null(cachedInverse)) {
return(cachedInverse)
}
inverse <- solve(x$get())
x$setCachedInverse(inverse)
inverse
}
#used for testing, creates a solvable n by n matrix
createSolveableMatrix <- function(n) {
mat <- matrix(0, nrow=n, ncol=n)
for (i in 1:n) {
mat[i,i] = i
}
mat
}