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
43 lines (40 loc) · 1.41 KB
/
Copy pathcachematrix.R
File metadata and controls
43 lines (40 loc) · 1.41 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
## These functions transform a a matrix into a list,
## with the precalculated(cached) inverse value stored on it.
## You must always initialize your matrix with makeCacheMatrix
## before using on cacheSolve
## Example usage:
## my_matrix=matrix(c(1,2,3,4), nrow=2)
## my_cached_matrix = makeCacheMatrix(my_matrix)
## cacheSolve(my_cached_matrix) # first call, will calculate
## cacheSolve(my_cached_matrix) # second call, will fetch from cache and print 'getting cache data'
## Creates a list containing 4 functions
## get: returns the value passed as x
## set: sets the value stored inside, retrieved by x
## setinverse: sets the stored inv value (you must pass it, this function does not calculate)
## getinverse: returns the stored inv value.
makeCacheMatrix <- function(x = matrix()) {
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)
}
## Return a matrix that is the inverse of 'x'.
## If x already was calculated, fetch from cache
cacheSolve <- function(x, ...) {
m <- x$getinverse()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- solve(data, ...)
x$setinverse(m)
m
}