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 (59 loc) · 2.15 KB
/
cachematrix.R
File metadata and controls
68 lines (59 loc) · 2.15 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
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
# The function takes a matrix x as an input
# it defines the following in its scope:
# variable "inversion" intead to hold the inverse
# four functions:
# 1- set
# 2- get
# 3- setinversion
# 4- getinversion
#
# The set function uses the <<- operator to assign the values defined at the scope of makeCacheMatrix environment level.
# The following three functions have x and inversion as free variables that aren't defined within their scopes,
# so they search on the parent level - which is makeCacheMatrix level - in which they are defined.
# accordingly they are able to set the variables using the <<- operator.
#
# the get points to a function that returns the matrix
# the getinv points to a function that returns the inversion of the matrix.
#
# the function returns a list that holds the four functions
makeCacheMatrix <- function(x = matrix()) {
inversion <- NULL
## Set Matrix
set <- function(y) {
x <<- y
inversion <<- NULL
}
#Get Matrix
get <- function() x
#Set cached matrix
setCache <- function(inverted_matrix) inversion <<- inverted_matrix
#Get cached matrix
getCache <- function() inversion
#Return list of functions
list(set = set, get = get,
setCache = setCache,
getCache = getCache)
}
## Write a short comment describing this function
# the function checks if the inversion matrix exists or not with the function call getCache()
#
# if the call returns a not null value then the inverted matrix exists in cache and hence that value is returned.
#
# Finally, the inverted matrix is cached in the makeCacheMatrix list using the function setCache(inversion)
cacheSolve <- function(x, ...) {
## Check if the inversion matrix exists
inversion <- x$getCache()
if(!is.null(inversion)) {
message("Retrieving from cache")
return(inversion)
}
## Not in cache and hence calculate inversion using solve.
data <- x$get()
inversion <- solve(data, ...)
##Set Inversion Matrix in cache
x$setCache(inversion)
inversion
}