Repository navigation
Expand file tree
/
Copy pathcachematrix.R
More file actions
62 lines (49 loc) · 1.92 KB
/
Copy pathcachematrix.R
File metadata and controls
62 lines (49 loc) · 1.92 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
## Call makeCacheMatrix with a square matrix first
## then call cacheSolve and pass the makeCacheMatrix
## to get the inverse
## -------------------------------------------------------------------------
## Make a cacheable Matrix
## call this function First!
## Parameters: x: invertible or nonsingular square matrix
## Returns cachaable Matrix Object
## -------------------------------------------------------------------------
makeCacheMatrix <- function(x = matrix()) {
mInverse <- NULL ##Variable to store the inverse
##Constructor. Initialize CacheMatrix
set <- function(newMatrix) {
x <<- newMatrix
mInverse <<- NULL
}
get <- function() x
##Set the inverse, to be called by cacheSolve
setInverse<- function(inverse) mInverse <<- inverse
##Get the stored inverse, to be called by cacheSolve, may be null (first time)
getInverse <- function() mInverse
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## -------------------------------------------------------------------------
## Return the Inverse of a cacheable Matrix object (makeCacheMatrix)
## If necessary calculate the inverse and set the inverse in makeCacheMatrix
## Parameters: x: makeCacheMatrix
## Return: inverse of matrix from makeCacheMatrix
## -------------------------------------------------------------------------
cacheSolve <- function(x, ...) {
mInv <- x$getInverse()
##Is there a inverse already calculated?
if(!is.null(mInv)) {
##Inverse found return cache
message("getting cached data")
return(mInv)
}
##No inverse available. Calculation required
##Get Matrix
data <- x$get()
##Calculate Inverse
mInverse <- solve(data, ...)
##Set inverse in makeCacheMatrix
x$setInverse(mInverse)
##Return Inverse
mInverse
}