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
94 lines (72 loc) · 2.54 KB
/
Copy pathcachematrix.R
File metadata and controls
94 lines (72 loc) · 2.54 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
83
84
85
86
87
88
89
90
91
92
93
94
# =============================================================================
# Programming Assignment 2
# Carlos Ruiz (cruizch@gmail.com)
# 2014-08-19
# =============================================================================
# =============================================================================
# makeCacheMatrix
# function that creates a cached inverse matrix object
#
# Carlos Ruiz (cruizch@gmail.com)
# 2014-08-19
# =============================================================================
# m matrix object
# =============================================================================
makeCacheMatrix <- function(m = matrix()) {
inv <- NULL
set <- function(x) {
m <<- x
inv <<- NULL
}
get <- function() {
m
}
setInverse <- function(inverse) {
inv <<- inverse
}
getInverse <- function() {
inv
}
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
}
# =============================================================================
# cacheSolved
#
# function that calculates the matrix inverse (just the first time) or gets the
# cached matrix inverse
#
# Carlos Ruiz (cruizch@gmail.com)
# 2014-08-19
# =============================================================================
# m cache matrix object
# =============================================================================
cacheSolve <- function(m, ...) {
inv <- m$getInverse()
if(!is.null(inv)) {
message("get the cached matrix inverse")
return(inv)
}
# for this assignment we assume that the matrix is invertible, but we can
# use the ginv function of the MASS package to get a generalized inverse,
# so if the matrix is invertible then solve(m) == ginv(v)
inv <- solve(m$get(), ...)
m$setInverse(inv)
inv
}
# ============================================================================
# the following code is for test purposes
# Carlos Ruiz (cruizch@gmail.com)
# 2014-08-19
# ============================================================================
# test matrix
test <- matrix(data = c(1, 1, 0, 1, 0, 1, 0, 1, 0), nrow = 3, ncol = 3)
# construct a cache matrix object
myMatrix <- makeCacheMatrix(test)
# access to the current inverse, must return null
myMatrix$getInverse()
# calculate the matrix inverse
cacheSolve(myMatrix)
# access to the current inverse, must be not null
myMatrix$getInverse()
# must print cache access and return the cached matrix inverse
cacheSolve(myMatrix)