forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
54 lines (46 loc) · 1.77 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
## Calculates the inverse of a matrix. In order to save time and resources,
## first check if the inverse already exists from previous operations, if so
## it loads it from the cache, if not, it calculates it and stores it in
## cache for later use.
## This helper function creates a special matrix that:
## 1. Set the matrix
## 2. Get the matrix
## 3. Set the inverse of the matrix
## 4. Get the inverse of the matrix
makeCacheMatrix <- function(x = matrix()) {
## The get/set method are similar to provided example, using matrix type
m <- NULL
set <- function(y){
## stores the x and m matrixes in the upper environment, where
## they can be accessed
x <<- y
m <<- NULL
}
get <- function() x
## this is where we calculate the inverse
setinverse <- function(solve) m <<- solve
getinverse <- function() return(m)
## finally we return the object created with these functions as a list
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## This function calculates the inverse of a matrix using the makeCacheMatrix
## function if the matrix already exists, it retrieves it from the cache, if
## not, it calculates the inverse and store it for later use.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$getinverse()
## check if it is already in the cache and return it if so
if(!is.null(m)){
message("getting the cached inverse matrix")
return(m)
}
## if it is not in cache, it sends the matrix to cache calculating the
## inverse in the process and storing it
data <- x$get()
m <- solve(data, ...)
x$setinverse(m)
## finally it returns the inverse matrix
return(m)
}