forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
69 lines (59 loc) · 1.69 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
## Here we have two functions:
## The first one cache the inverse of a matrix
## The second one computes de inverse of a matrix
## This function receive a matrix as a parameter, create an object
## that stores the inverse of the given matrix
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setinv <- function(solve) m <<- solve
getinv <- function() m
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
## ## The following is a pair of functions that cache and compute the
## inverse of a matrix.
## This function creates a special "matrix" object
## that can cache its inverse.
makeCacheMatrix <- function(mtx = matrix()) {
inverse <- NULL
set <- function(x) {
mtx <<- x;
inverse <<- NULL;
}
get <- function() return(mtx);
setinv <- function(inv) inverse <<- inv;
getinv <- function() return(inverse);
return(list(set = set, get = get, setinv = setinv, getinv = getinv))
}
## This function calculates the inverse of the matrix returned by the previous function
## If the inverse has already been calculated, then the following function should just
## retrieve the inverse from the "store" variable.
cacheSolve <- function(mtx, ...) {
inverse <- mtx$getinv()
if(!is.null(inverse)) {
message("Getting cached data...")
return(inverse)
}
data <- mtx$get()
invserse <- solve(data, ...)
mtx$setinv(inverse)
return(inverse)
}
cacheSolve <- function(x, ...) {
m <- x$getinv()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- solve(data, ...)
x$setinv(m)
m
## Return a matrix that is the inverse of 'x'
}