Repository navigation
Expand file tree
/
Copy pathcachematrix.R
More file actions
61 lines (51 loc) · 1.62 KB
/
Copy pathcachematrix.R
File metadata and controls
61 lines (51 loc) · 1.62 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
## makeCacheMatrix function does the following things
## 1. set the value of the matrix
## 2. get the value of the matrix
## 3. set the value of inverse of the matrix
## 4. get the value of inverse of the matrix
makeCacheMatrix <- function(x = matrix()) {
invm <- NULL
set <- function(y) {
x <<- y
invm <<- NULL
}
get <- function() x
setinverse <- function(inverse) invm <<- inverse
getinverse <- function() invm
list(set=set, get=get, setinverse=setinverse, getinverse=getinverse)
}
##cacheSolve function returns the inverse of the matrix.
##If the inverse is already present it will take the
##value from cache and skips the computation part.
##If the inverse value is not present then it will
##compute the inverse of the matrix specified.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
invm <- x$getinverse()
if(!is.null(invm)) {
message("getting cached data.")
return(invm)
}
data <- x$get()
invm <- solve(data)
x$setinverse(invm)
invm
}
## How to run the program to test ## the functions created
## >x = rbind(c(1, 2), c(2, 1))
## > m = makeCacheMatrix(x)
## > m$get()
## [,1] [,2]
## [1,] 1 2
## [2,] 2 1
## When we run it for the first time the results are not from cache
## > cacheSolve(m)
## [,1] [,2]
## [1,] -0.3333333 0.6666667
## [2,] 0.6666667 -0.3333333
## When we run the second time the values are obtained from the ## cache
## > cacheSolve(m)
## getting cached data.
## [,1] [,2]
## [1,] -0.3333333 0.6666667
## [2,] 0.6666667 -0.3333333