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
65 lines (40 loc) · 1.59 KB
/
cachematrix.R
File metadata and controls
65 lines (40 loc) · 1.59 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
## As indicated, matrix inversion could be computationally expensive
## Using the <<- operator it is possible to store the inversions of a matrix for later use
## makeCacheMatrix creates a matrix and store it in the environment
## if the value is not null, the assumption being the matrix is relevant
## for later use and should be cached accordingly
makeCacheMatrix <- function(x = matrix()) {
myi<- NULL
set <- function(m){
if(is.null(m))
x <<-m
}
get <- function() x
setInverse <- function(myinverse) {
if(is.null(myinverse))
myinverse<- solve(x)
myi <<- myinverse
}
getInverse <- function() myi
list (set=set,get=get, setInverse=setInverse,getInverse=getInverse)
}
## solve method can be used for computing the inverse of a square matrix
## saving the result of the inverse of a matrix can therefore be useful
## cacheSolve retrives the values of a saved result of an inverse of a matrix
cacheSolve <- function(x, ...) {
## Retrive the matrix from cache using getter method
cachedMatrix <- x$get()
## Check if isn't null and its inverse has been computed
if(!is.null(cachedMatrix)){
if(is.null(x$getInverse())){
x$setInverse(NULL)
}
return (x$getInverse())
}
## Otherwise compute the inverse using solve method
matrix_data <- x$get()
inversedResult <- solve(matrix_data)
## And dont't forget storing it to the cache
x$setInverse(inversedResult)
inversedResult
}