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
76 lines (68 loc) · 2.38 KB
/
cachematrix.R
File metadata and controls
76 lines (68 loc) · 2.38 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
# --------------------------
## cachematrix.R -----------
## Two functions that cache then inverse a matrix.
# --------------------------
# --------------------------
# makeCacheMatrix
# Description --------------
# Creates a matrix cache object that can be inversed.
# Usage--------------------
# makeCacheMatrix(cacheMatrix)
# Arguments----------------
# cacheMatrix a matrix to be cached
# -------------------------
makeCacheMatrix <- function(cacheMatrix = matrix()) {
# object to store the inverse matrix, initializes to NULL
invMatrix <- NULL
# initialize cache matrix outside current environment
setMatrix <- function(ext) {
cacheMatrix <<- ext
invMatrix <<- NULL
}
# return the value of the cached matrix previously set
getMatrix <- function() {
cacheMatrix
}
# store the inverse of the matrix
setinverseMatrix <- function(inverseMatrix){
invMatrix <<- inverseMatrix
}
# return the value of the cached inverse
getinverseMatrix <- function(){
invMatrix
}
list(setMatrix = setMatrix, getMatrix = getMatrix,
setinverseMatrix = setinverseMatrix, getinverseMatrix = getinverseMatrix)
}
# -------------------------
# cacheSolve
# Description -------------
# Computes and returns the inverse of the cached "matrix" object.
# Usage--------------------
# cacheSolve(cachedMatrix, ...)
# Argument-----------------
# cachedMatrix cached matrix object
# ... other arguments passed to or from other functions
# -------------------------
cacheSolve <- function(cachedMatrix, ...) {
# Retrieve inversed matrix cached object passed from the parent frame
inverseMatrix <- cachedMatrix$getinverseMatrix()
# If cached object already contains an inversed matrix
if (!is.null(inverseMatrix)){
message("retrieved cached data")
# return cached inversed matrix
return (inverseMatrix)
}
# if the inverse matrix hasn't been cached,
# grab the cached matrix
else {
tmpMatrix <- cachedMatrix$getMatrix()
message("building inverse matrix")
# Inverse the data matrix
inverseMatrix <- solve(data, ...)
# Cache inversed matrix
cachedMatrix$setinverseMtrix(inverseMatrix)
# Return the inversed matrix
return (inverseMatrix)
}
}