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
60 lines (43 loc) · 1.72 KB
/
cachematrix.R
File metadata and controls
60 lines (43 loc) · 1.72 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
## Functions to practice the concepts of lexical scoping in R
## In this example the functions store the value of the inverse of a matrix so as to avoid repeating the calculation
## later in the program.
## Define the structure of the object that stores and retrieves the inverse matrix using the functions:
##
## set: initializes the value of the inverse matrix to NULL and stores the matrix
## get: retrieves the matrix
## setinv: stores the inverse
## getinv: retrieves the inverse
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setinv <- function(inverse) inv <<- inverse
getinv <- function() inv
## Returns the list of functions to be used later in cacheSolve
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
## Computes the inverse of the matrix using the functions defined in makeCacheMatrix
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
## get the stored inverse matrix
inv <- x$getinv()
##if is not NULL means that the inverse has been calculated previouly and returns it
if(!is.null(inv)) {
message("getting the inverse matrix from the cache")
return(inv)
}
## if the program arrives here means that the inverse must be calculated
## get the matrix to be inverted
data <- x$get()
## compute the inverse
inv <- solve(data, ...)
## store the inverse
x$setinv(inv)
## return the inverse
inv
}