Skip to content

Commit 065292b

Browse files
JyeJye
authored andcommitted
Refactoring
Inverted if statement to eliminate early return Fixed some comments
1 parent b6254b0 commit 065292b

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

cachematrix.R

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,13 @@
44
##Create a matrix whose inverse can be cached
55
makeCacheMatrix <- function(x = matrix()) {
66
inverse <- NULL
7+
8+
##Assigns a new matrix and invalidates the inverse cache
79
set <- function(y) {
810
x <<- y
911
inverse <<- NULL
1012
}
13+
1114
get <- function() x
1215
setInverse <- function(i) inverse <<- i
1316
getInverse <- function() inverse
@@ -16,14 +19,14 @@ makeCacheMatrix <- function(x = matrix()) {
1619

1720
## Returns the cached inverse of matrix 'x'. If inverse of 'x' is not cached, it is calculated and cached.
1821
cacheSolve <- function(x, ...) {
19-
## Return a matrix that is the inverse of 'x'
22+
23+
##Calculate and cache inverse if necessary
2024
inverse <- x$getInverse()
21-
if (!is.null(inverse)) {
22-
message("getting cached data")
23-
return(inverse)
25+
if (is.null(inverse)) {
26+
data <- x$get()
27+
inverse <- solve(data, ...)
28+
x$setInverse(inverse)
2429
}
25-
data <- x$get()
26-
inverse <- solve(data, ...)
27-
x$setInverse(inverse)
28-
inverse
30+
31+
x$getInverse()
2932
}

0 commit comments

Comments
 (0)