forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cachematrix.R
55 lines (49 loc) · 2.08 KB
/
cachematrix.R
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
## The makeCacheMatrix constructs a suitable object that can store the value
## of both the direct and cached inverse.It should be used in combination with cacheSolve
## that, when called, before perforimg the computation of the inverse checks for the cached variable
## if not found computes the inverse and caches it in the object returned by makeCacheMatrix
## usage example
## > set.seed(44)
## > m <- matrix(sample.int(100,size=9,replace=TRUE), nrow=3)
## > d <- makeCacheMatrix(m)
## > cacheSolve(d)
## subsequent invocation returns cached data
## > inv <- cacheSolve(d)
## returning cached data
## makeCacheMatrix stores in variable i the inverse and provides accessor methods for both
## the data (ie the matrix one wants to calculate the inverse) and the inverse itself
makeCacheMatrix <- function(x = matrix()) {
i <- NULL
set <- function(y) {
x <<- y
i <<- NULL
}
get <- function() x
setinverse <- function(inverse) i <<- inverse
getinverse <- function() i
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## cacheSolve searches for a cached value of the inverse matrix one wants to calculate
## by accessing the object provided by the makeCacheMatrix function and invoking the getinverse() function
## implemented in the first part of the exercise.
# if founded (the object returned by the method is not null) returns it and exit the function
# otherwise accesses again the object
## gets the data (the matrix one wants to calcutlate the inverse)
## invokes the solve functions provided by R base system to compute the inverse,
## stores the inverse for future invocations on the same variable passed and finally returns inverse
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getinverse()
if(!is.null(inv)){
## Data already cached
message("returning cached data")
return(inv)
}
## no data cached accessing the matrix and computing the inverse
data <- x$get()
inv <- solve(data, ...)
x$setinverse(inv)
inv
}