forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
57 lines (48 loc) · 1.54 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
54
55
56
57
## These functions are meant for implementing cached version of
## solve function. The solution is based on a special kind of matrix
## that can cache the results of the solve function.
##
## Example usage:
## matrx = makeCacheMatrix()
## B = matrix( c(1, 2, 3, 4),nrow=2, ncol=2)
## matrx$setMatrix(B)
## result = cacheSolve(matrx)
## print(result)
## makeCacheMatrix function creates a matrix that can store results of
## matrix inverse in cache.
## Functions available in created matrix: setMatrix, getMatrix, setInverse, getInverse
makeCacheMatrix <- function(x = matrix()) {
i <- NULL
setMatrix <- function(y) {
m <<- y
i <<- NULL
}
getMatrix <- function() m
setInverse <- function(inverse) i <<- inverse
getInverse <- function() i
list(setMatrix = setMatrix, getMatrix = getMatrix,
setInverse = setInverse,
getInverse = getInverse)
}
## cacheSolve function calculates matrix inverse. If result has already
## been calculated and cached then function results cached result instead
cacheSolve <- function(x, ...) {
i <- x$getInverse()
## Check if cached result exists
if(!is.null(i)) {
return(m)
}
data <- x$getMatrix()
## calculate inverse matrix
i <- solve(data, ...)
x$setInverse(i)
i
}
## Function for testing the functionality of the cached matrix
testCachedMatrix <- function() {
matrx = makeCacheMatrix()
B = matrix( c(1, 2, 3, 4),nrow=2, ncol=2)
matrx$setMatrix(B)
result = cacheSolve(matrx)
print(result)
}