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
82 lines (61 loc) · 1.9 KB
/
cachematrix.R
File metadata and controls
82 lines (61 loc) · 1.9 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
## These two functions optimize the calculation of the inverse of a matrix.
## The first makeCacheMatrix(m = matrix()) build an object that is
## capable to store a matrix and its inverse, the first time when
## it is calculated. If the content (the matrix) changes, the cached
## inverse will be deleted.
## The second function performs the calculation
##
## Usage:
## cm <- makeCacheMatrix(matrix(c(1,0,0,1),nrow=2,byrow=TRUE))
## cacheSolve(cm)
##
## Another example: calculate inverse and verify that
## the product is the identity matrix.
##
## cm <- makeCacheMatrix(diag(c(2,1),nrow=2,ncol=2))
##
## cacheSolve(cm)
## [,1] [,2]
##[1,] 0.5 0
##[2,] 0.0 1
## mc <- cacheSolve(cm)
## cm$get() %*% mc
## [,1] [,2]
## [1,] 1 0
## [2,] 0 1
## This function build an object (represented with a list)
## to model a matrix which supports the caching of inverse
## calculation. The list is made by sub-functions that
## let to set the matrix, its inverse, and to get both, via methods
## set(), setinverse(), get(), getinverse().
makeCacheMatrix <- function(x = matrix()) {
## Return a list which represents
## a matrix with a cacheable inverse
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setinverse <- function(inverse) inv <<- inverse
getinverse <- function() inv
list(set = set, get = get,
setinverse = setinverse, getinverse = getinverse)
}
## This function takes a cache matrix as argument
## and return its inverse. It calculates the inverse only when necessary:
## the first time when it's being invoked. Successive invocations,
## if the matrix content isn't changed, will return the
## cached value
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
i <- x$getinverse()
if (!is.null(i)) {
message("getting cached inverse")
return (i)
}
data <- x$get()
i <- solve(data, ...)
x$setinverse(i)
i
}