forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
73 lines (55 loc) · 2.45 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
70
71
72
73
## File: cachematrix.R, a function for the 2nd Assignment of the R programming course
## Web: https://class.coursera.org/rprog-002/
## Authors: rdpeng, gabrielfc
## Date: 2014/04
## Description: This R script has 2 functions: makeCacheMatrix and cacheSolve, used to
## cache the inverse of a matrix in order to reduce the cost of computing it repeatedly.
## Use Example:
## m<-makeCacheMatrix(matrix(8:11,nrow=2))
## cacheSolve(m) ## Inverse calculated
## cacheSolve(m) ## Inverse retrieved from cache, not calculated
## makeCacheMatrix creates a special matrix object that can cache its inverse.
makeCacheMatrix <- function(x = matrix()) {
## Iniatialize the variable that will store the inverse matrix.
invertedMatrix <- NULL
## 1.- If a (new) matrix (y) is passed to the function
setMatrixCache <- function(y) {
## Set the matrix value to the cache
x <<- y
## Restart the variable to NULL.
invertedMatrix <<- NULL
}
## 2.- Retrieve the matrix stored in the cache
getMatrixCache <- function() x
## 3.- Save the inverted matrix to the cache
setInvertedMatrixCache <- function(solve) invertedMatrix <<- solve
## 4.- Get the inverted matrix from the cache
getInvertedMatrixCache <- function() invertedMatrix
## A simple list of the 4 functions.
list(setMatrixCache=setMatrixCache,
getMatrixCache=getMatrixCache,
setInvertedMatrixCache=setInvertedMatrixCache,
getInvertedMatrixCache=getInvertedMatrixCache)
}
## cacheSolve is a function that checks if the inverted matrix (solved
## matrix) for a given matrix (x) is stored in the cache. If it is,
## it retrieves the previous results. If not, it solves the matrix.
cacheSolve <- function(x, ...) {
## Try to get the result of the previous inverted matrix from the cache.
invertedMatrix <- x$getInvertedMatrixCache()
## If the results is not NULL, means the matrix has already been inverted
## and the script ends returning it form cache. No solving this time.
if(!is.null(invertedMatrix)) {
message("getting inverse matrix from cache")
return(invertedMatrix)
} else {
## If the invertedMatrix has not been solved yet, get the new matrix
inputMatrix <- x$getMatrixCache()
## And solve (inverse) the matrix.
invertedMatrix <- solve(inputMatrix)
## Save the inverted matrix to the cache.
x$setInvertedMatrixCache(invertedMatrix)
## Return the result.
return(invertedMatrix)
}
}