Skip to content

Commit 70d672f

Browse files
committed
comments added
1 parent 2e9773c commit 70d672f

File tree

2 files changed

+21
-15
lines changed

2 files changed

+21
-15
lines changed

.Rhistory

Whitespace-only changes.

cachematrix.R

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,17 @@
88

99
makeCacheMatrix <- function(x = matrix()) {
1010
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
1416
}
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
1922
}
2023

2124

@@ -24,15 +27,18 @@ makeCacheMatrix <- function(x = matrix()) {
2427
# It first checks if the inverse of matrix exists in getinv() of
2528
# makeCacheMatrix() and returns it if available. If not available then
2629
# calculates it using solve() and returns the answer.
27-
cacheSolve <- function(x, ...) {
30+
31+
cacheSolve <- function(x, ...) { # Takes makeCacheMatrix() object as input
2832
## 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
3337
}
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()
3743
inv
3844
}

0 commit comments

Comments
 (0)