Repository navigation
Expand file tree
/
Copy pathcachematrix.R
More file actions
84 lines (46 loc) · 2.51 KB
/
Copy pathcachematrix.R
File metadata and controls
84 lines (46 loc) · 2.51 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
## Here two functions 'makeCacheMatrix()' and 'cacheSolve()' functions are implemented.
## 'makeCachematrix()' takes a matrix as a argument and return a list of functions.
## 'cacheSolve()' takes a matrix object and calculate its inverse and if already
## existed in cache then simply return that.
## Here 'solve()' functions is used to calculate inverse, which takes square matrix
## and if it is invertible then return inverse. So, square invertible matrix is
## given as a input matrix.
## 'makeCachematrix()' takes a matrix as a argument and return a list of functions
## named 'set()', 'get()', 'setinverse()' and 'getinverse()'.
makeCacheMatrix <- function(x = matrix()) {
## intially inverse matrix is NULL.
inverse <- NULL
## Set the value of matrix.
set <- function(y){
x <<- y
inverse <<- NULL
}
## Get the value of matrix.
get <- function() x
## Set the value of inverse matrix.
setinverse <- function(minverse) inverse <<- minverse
## Get the value of inverse matrix.
getinverse <- function() inverse
## Return a list of functions.
list(set = set, get = get, setinverse = setinverse, getinverse = getinverse)
}
## 'cacheSolve()' takes a matrix object and calculate its inverse and if already
## existed in cache then simply return that. solve() is used to calculate matrix
## inverse and return the inverse matrix.
cacheSolve <- function(x, ...) {
## Get inverse matrix .
inverse <- x$getinverse()
## if inverse matrix is previously computed then return that.
if(!is.null(inverse)){
message("Getting cached data")
return(inverse)
}
## Get the matrix.
data <- x$get()
## Calculate the inverse.
inverse <- solve(data, ...)
## Set the inverse.
x$setinverse(inverse)
## Return a matrix that is the inverse of 'x'.
inverse
}