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
45 lines (36 loc) · 1.6 KB
/
Copy pathcachematrix.R
File metadata and controls
45 lines (36 loc) · 1.6 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
## Put comments here that give an overall description of what your
## functions do
## The function 'makeCacheMatrix' takes an optional matrix parameter representing the matrix to be inverted.
## The default valuse is an empty matrix.
## The function contains two data fields - the original matrix and the inverted matrix, and getter and setter funcions for these fields.
## The function serves as a container only, it does not calculate the inversion.
## If the original matrix value is changed via set method, the inverted value is nullified automatically.
## The function returns a list of accessor functions - get/set for the original martix, and getInverse/setInverse for the inverted matrix
makeCacheMatrix <- function(x = matrix()) {
inverseX <- NULL
set <- function(y) {
x <<- y
inverseX <<- NULL
}
get <- function() {x}
setInverse <- function(inverse) {
inverseX <<- inverse
}
getInverse <- function() {inverseX}
list(set=set, get=get, setInverse=setInverse, getInverse=getInverse)
}
## The function 'cacheSolve' accepts a "cache" matrix created by the 'makeCacheMatrix' function.
## It first checks whether the inverted matrix is already cached, and if yes - returns it.
## Otherwise this function calculates the inverted matrix, saves it in the cache, and then returns it
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
res <- x$getInverse()
if (!is.null(res)) {
message('returning cached data')
return(res)
}
m <- x$get()
res <- solve(m)
x$setInverse(res)
res
}