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
82 lines (64 loc) · 2.62 KB
/
Copy pathcachematrix.R
File metadata and controls
82 lines (64 loc) · 2.62 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
## Matrix inversion is usually a costly computation, and so there may be some benefit
## to caching the inverse of a matrix rather than compute it repeatedly. The functions
## below calculate and cache the inverse of a matrix.
## makeCacheMatrix creates a special "matrix" object that can cache its inverse
makeCacheMatrix <- function(x = matrix()) {
i <- NULL
set <- function(y) {
x <<- y
i <<- NULL
}
get <- function() x
setInverse <- function(inverse) i <<- inverse
getInverse <- function() i
list(set=set,
get=get,
setInverse=setInverse,
getInverse=getInverse)
}
## cacheSolve computes the inverse of the special "matrix" returned by makeCacheMatrix
## (above). If the inverse has already been calculated (and the matrix has not changed),
## then the cachesolve should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
i <- x$getInverse()
if(!is.null(i)) {
message("getting cached data")
return(i)
} else {
message("calculating inverse")
data <- x$get()
i <- solve(data)
x$setInverse(i)
return(i)
}
}
## ---- test 1 (3x3) ----
matrix_3x3 <- matrix(c(3,0,2,2,0,-2,0,1,1), 3, 3, byrow=TRUE) # from: https://www.mathsisfun.com/algebra/matrix-inverse-row-operations-gauss-jordan.html
test_matrix <- makeCacheMatrix(matrix_3x3)
test_matrix$get()
## first time through, should get inverse w/ message: "calculating inverse"
test_matrix$setInverse(NULL)
cacheSolve(test_matrix)
## second time through, should get inverse w/ message: "calculating inverse"
cacheSolve(test_matrix)
## ---- test 3 (4x4) ----
matrix_4x4 <- matrix(c(4,0,0,0,0,0,2,0,0,1,2,0,1,0,0,1), 4, 4, byrow=TRUE) # from https://www.mathsisfun.com/algebra/matrix-inverse-row-operations-gauss-jordan.html
matrix_4x4
test_matrix <- makeCacheMatrix(matrix_4x4)
test_matrix$get()
## first time through, should get inverse w/ message: "calculating inverse"
test_matrix$setInverse(NULL)
cacheSolve(test_matrix)
## second time through, should get inverse w/ message: "calculating inverse"
cacheSolve(test_matrix)
## ---- test 5 (set function : from 4x4 to 3x3) ----
test_matrix <- makeCacheMatrix(matrix_4x4)
test_matrix$get()
test_matrix$set(matrix_3x3)
test_matrix$get()
## first time through, should get inverse (calculate)
test_matrix$setInverse(NULL)
cacheSolve(test_matrix)
## second time through, should get inverse (cache)
cacheSolve(test_matrix)