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
68 lines (58 loc) · 1.77 KB
/
cachematrix.R
File metadata and controls
68 lines (58 loc) · 1.77 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
## Functions for manipulating the cacheable matrices
## Creates a cacheable matrix.
## List of the functions
## which operate with the variables within its own scope
## set(y)
## get()
## set.inverted(inverted)
## get.inverted()
makeCacheMatrix <- function(matrix.original = matrix()) {
# since we don't have type control in R
# we have to check whether the matrix was passed
if (!is.matrix(matrix.original)) {
stop("makeCacheMatrix expects argument to be a matrix")
}
matrix.inverted <- NULL
set <- function(y) {
matrix.original <<- y
matrix.inverted <<- NULL
}
get <- function(){
matrix.original
}
get.inverted <- function() {
matrix.inverted
}
set.inverted <- function(inverted) {
matrix.inverted <<- inverted
}
list(
set = set,
get = get,
set.inverted = set.inverted,
get.inverted = get.inverted
)
}
## checks if cacheable matrix contains a cached inverted matrix
## and returns
## I have a strong feeling that
## this function should be in a makeCacheMatrix
## and implement a singleton pattern
## But there are probably some specific things about R
## that don't allow this to happen
cacheSolve <- function(matrix.cacheable, ...) {
matrix.inverted <- matrix.cacheable$get.inverted()
#return matrix.inverted if it was computed and cached before
if (!is.null(matrix.inverted)) {
message("getting cached data")
return(matrix.inverted)
}
# otherwise: get the original one
matrix.original <- matrix.cacheable$get()
# calculate the inversed
matrix.inverted <- solve(matrix.original)
# store it for the future use
matrix.cacheable$set.inverted(matrix.inverted)
# and return it
matrix.inverted
}