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
46 lines (43 loc) · 1.38 KB
/
Copy pathcachematrix.R
File metadata and controls
46 lines (43 loc) · 1.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
## The next two functions create an object which can hold a matrix and cache its inverse and allow to work with it.
## This function creates a special "matrix" object that can cache its inverse (inv)
makeCacheMatrix <- function(x = matrix()) {
## initialize
inv <- NULL
setmatrix <- function(y) {
x <<- y
## setting new matrix - MUST clear the saved inverse!
inv <<- NULL
}
## getting a matrix
getmatrix <- function() {
x
}
## writing a matrix inverse into cash
writeinverse <- function(cached) {
inv <<- cached
}
## reading a matrix inverse from cashe, if possible
cachedinverse <- function() {
inv
}
list(set = setmatrix, get = getmatrix,
savetocache = writeinverse,
readfromcache = cachedinverse)
}
## This function returns the inverse of the special "matrix" made by makeCacheMatrix
## above. If the cashed inverse is valid (it has been calculated and the matrix itself has not changed)
## then the cacheSolve should retrieve the inverse from the cache, otherwise it will call solve()
cacheSolve <- function(x, ...) {
inverse <- x$readfromcache()
if(!is.null(inverse)) {
message("cached value found!")
## we have a valid inverse - return it!
return(inverse)
}
## not so lucky - we have to solve matrix...
data <- x$get()
inverse <- solve(data)
## ...and to cache solved matrix
x$savetocache(inverse)
inverse
}