forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcachematrix.R
More file actions
55 lines (44 loc) · 1.23 KB
/
cachematrix.R
File metadata and controls
55 lines (44 loc) · 1.23 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
##
## Programming assignment number 2 from Coursera R Programming course
##
## Assignment: Caching the Inverse of a Matrix
## Write a pair of functions that cache the inverse of a matrix.
##
## A function that creates a matrix whose inverse can be cached
makeCacheMatrix <- function(x = matrix()) {
## Private fields
inv <- NULL
## Getters and setters
get <- function() {
return(x)
}
set <- function(y){
x <<- y
inv <<- NULL
}
getInverse <- function() inv
setInverse <- function(inverse){
inv <<- inverse
}
## Return the list
list(get = get,
set = set,
getInverse = getInverse,
setInverse = setInverse)
}
## A function that returns the cached inverse of a matrix if such exists;
## otherwise calculates the inverse and caches it for future use.
cacheSolve <- function(x, ...) {
## Check if the inverse is already calculated and cached
inv <- x$getInverse()
if(!is.null(inv)){
message("Returning the cached inverse.")
return(inv)
}
## At this point the inverse is NULL; calculate and cache it
m <- x$get()
inv <- solve(m, ...)
x$setInverse(inv)
## Return the inverse
inv
}