1
- # # Put comments here that give an overall description of what your
2
- # # functions do
1
+ # Our aim in this experiment is to write a pair of functions, namely,
2
+ # "makeCacheMatrix" and "cacheSolve" that cache the inverse of a matrix
3
3
4
- # # Write a short comment describing this function
4
+ # makeCacheMatrix is a function which creates a special "matrix" object that can
5
+ # cache its inverse for the input (which is an invertible square matrix)
5
6
6
7
makeCacheMatrix <- function (x = matrix ()) {
7
-
8
+ inv <- NULL
9
+ set <- function (y ) {
10
+ x <<- y
11
+ inv <<- NULL
12
+ }
13
+ get <- function () x
14
+ setinv <- function (inverse ) inv <<- inverse
15
+ getinv <- function () inv
16
+ list (set = set , get = get , setinv = setinv , getinv = getinv )
8
17
}
9
18
10
19
11
- # # Write a short comment describing this function
20
+ # cacheSolve is a function which computes the inverse of the special "matrix"
21
+ # returned by makeCacheMatrix above. If the inverse has already been calculated
22
+ # (and the matrix has not changed), then the cachesolve should retrieve the
23
+ # inverse from the cache
12
24
13
25
cacheSolve <- function (x , ... ) {
14
- # # Return a matrix that is the inverse of 'x'
26
+ inv <- x $ getinv()
27
+ if (! is.null(inv )) {
28
+ message(" getting cached result" )
29
+ return (inv )
30
+ }
31
+ data <- x $ get()
32
+ inv <- solve(data , ... )
33
+ x $ setinv(inv )
34
+ inv
15
35
}
36
+
37
+
38
+ # Checking the Output-
39
+ my_matrix <- makeCacheMatrix(matrix (1 : 4 , 2 , 2 ))
40
+ my_matrix $ get()
41
+ # [,1] [,2]
42
+ # [1,] 1 3
43
+ # [2,] 2 4
44
+ my_matrix $ getinv()
45
+ # NULL
46
+ cacheSolve(my_matrix )
47
+ # [,1] [,2]
48
+ # [1,] -2 1.5
49
+ # [2,] 1 -0.5
50
+ my_matrix $ getinv()
51
+ # [,1] [,2]
52
+ # [1,] -2 1.5
53
+ # [2,] 1 -0.5
54
+
55
+
56
+ my_matrix $ set(matrix (c(2 , 2 , 1 , 4 ), 2 , 2 ))
57
+ my_matrix $ get()
58
+ # [,1] [,2]
59
+ # [1,] 2 1
60
+ # [2,] 2 4
61
+ my_matrix $ getinv()
62
+ # NULL
63
+ cacheSolve(my_matrix )
64
+ # [,1] [,2]
65
+ # [1,] 0.6666667 -0.1666667
66
+ # [2,] -0.3333333 0.3333333
67
+ cacheSolve(my_matrix )
68
+ # getting cached result
69
+ # [,1] [,2]
70
+ # [1,] 0.6666667 -0.1666667
71
+ # [2,] -0.3333333 0.3333333
72
+ my_matrix $ getinv()
73
+ # [,1] [,2]
74
+ # [1,] 0.6666667 -0.1666667
75
+ # [2,] -0.3333333 0.3333333
0 commit comments