8
8
9
9
makeCacheMatrix <- function (x = matrix ()) {
10
10
inv <- NULL
11
- set <- function (y ){
12
- x <<- y
13
- inv <<- NULL
11
+ # set() changes the values of argument x of makeCacheMatrix()
12
+ set <- function (y ){ # Takes y(matrix) as input
13
+ x <<- y # Assigns y to x in parent frame
14
+ inv <<- NULL # Since matrix is changed, inverse must be
15
+ # reassigned to NULL
14
16
}
15
- get <- function () x
16
- setinv <- function (sinv ) inv <<- sinv
17
- getinv <- function () inv
18
- list (set = set , get = get , setinv = setinv , getinv = getinv )
17
+ get <- function () x # returns matrix x
18
+ setinv <- function (sinv ) inv <<- sinv # Sets input as inv in parent
19
+ # frame
20
+ getinv <- function () inv # gets inv
21
+ list (set = set , get = get , setinv = setinv , getinv = getinv ) # List of 4 fs
19
22
}
20
23
21
24
@@ -24,15 +27,18 @@ makeCacheMatrix <- function(x = matrix()) {
24
27
# It first checks if the inverse of matrix exists in getinv() of
25
28
# makeCacheMatrix() and returns it if available. If not available then
26
29
# calculates it using solve() and returns the answer.
27
- cacheSolve <- function (x , ... ) {
30
+
31
+ cacheSolve <- function (x , ... ) { # Takes makeCacheMatrix() object as input
28
32
# # Return a matrix that is the inverse of 'x'
29
- inv <- x $ getinv()
30
- if (! is.null(inv )) {
31
- message(" getting cached data" )
32
- return (inv )
33
+ inv <- x $ getinv() # Gets getinv() from makeCacheMatrix()
34
+ if (! is.null(inv )) { # Checks if inv has stored value
35
+ message(" getting cached data" )
36
+ return (inv ) # returns inv
33
37
}
34
- data <- x $ get()
35
- inv <- solve(data , ... )
36
- x $ setinv(inv )
38
+ data <- x $ get() # if inv is not stored, get the matrix to be
39
+ # inverted and store in 'data'
40
+ inv <- solve(data , ... ) # Invert the matrix 'data'
41
+ x $ setinv(inv ) # store the inverse in makeCacheMatrix()
42
+ # using setinv()
37
43
inv
38
44
}
0 commit comments